Exercise
Saving Data To A Binary File
Objective
Develop a Python program that prompts the user to enter their name, age (as a byte), and birth year (as an integer), then saves this information into a binary file.
Additionally, implement a reader to verify that the data has been correctly written to the file.
Example Python Exercise
Show Python Code
import struct
def save_data_to_binary(file_name):
"""
Prompts the user for their name, age, and birth year, and saves this data into a binary file.
Parameters:
file_name (str): The name of the binary file to save the data.
"""
# Get user input
name = input("Enter your name: ")
age = int(input("Enter your age (as a byte): "))
birth_year = int(input("Enter your birth year: "))
# Ensure the age is within byte range (0-255)
if not (0 <= age <= 255):
print("Age must be between 0 and 255.")
return
# Open the binary file in write mode
with open(file_name, 'wb') as file:
# Pack the data into a binary format
# Name is encoded as a string, age as a byte (B), birth year as an integer (I)
# '20s' ensures the name is stored as a string of up to 20 characters (padded with null bytes)
data = struct.pack('20s B I', name.encode('utf-8'), age, birth_year)
file.write(data)
print(f"Data has been successfully written to {file_name}.")
def read_data_from_binary(file_name):
"""
Reads the binary file and prints the saved data.
Parameters:
file_name (str): The name of the binary file to read the data from.
"""
try:
with open(file_name, 'rb') as file:
# Read the binary data
data = file.read()
# Unpack the data: '20s B I' corresponds to a string (20 chars), a byte, and an integer
name, age, birth_year = struct.unpack('20s B I', data)
# Decode name from bytes and strip the null bytes
name = name.decode('utf-8').rstrip('\x00')
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Birth Year: {birth_year}")
except FileNotFoundError:
print(f"The file '{file_name}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Main program execution
if __name__ == "__main__":
file_name = 'user_data.bin'
# Save the data to binary file
save_data_to_binary(file_name)
# Read and verify the saved data
print("\nReading the saved data...\n")
read_data_from_binary(file_name)
Output
User Input:
Enter your name: John Doe
Enter your age (as a byte): 30
Enter your birth year: 1994
Program Output After Saving Data:
Data has been successfully written to user_data.bin.
Program Output After Reading Data:
Reading the saved data...
Name: John Doe
Age: 30
Birth Year: 1994
Share this Python Exercise