Saving Data to a Binary File - Python Programming Exercise

In this exercise, you will 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. This exercise is perfect for practicing file handling, data serialization, and user input in Python. By implementing this program, you will gain hands-on experience in handling file operations, data serialization, and user input in Python. This exercise not only reinforces your understanding of file handling but also helps you develop efficient coding practices for managing user interactions.

 Category

Managing Files

 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

 Copy 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

 More Python Programming Exercises of Managing Files

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  Reverse the contents of a text file

    In this exercise, you will develop a Python program that inverts the contents of a text file. This exercise is perfect for practicing file handling, loops, and...

  •  Working with binary GIF files

    In this exercise, you will develop a Python program to validate the structure of a GIF image file. This exercise is perfect for practicing file handling, byte ...

  •  Database of Contacts using File Storage

    In this exercise, you will develop a Python program that extends the "contacts database" by implementing functionality to load data from a file at the start of each s...

  •  Transform a Text File to Uppercase

    In this exercise, you will develop a Python program that reads the contents of a text file and writes it to a new file, converting all lowercase letters to uppercase....

  •  Transform any file content to uppercase

    In this exercise, you will develop a Python program that reads any file and transfers its content to another file, converting all lowercase letters to uppercase. This...

  •  Reversing File Content

    In this exercise, you will develop a Python program to "invert" a file. This exercise is perfect for practicing file handling, byte manipulation, and loops in ...