Binary File Reading (BMP Example) - Python Programming Exercise

In this exercise, you will develop a Python program that verifies if a BMP image file is valid by checking its header. This exercise is perfect for practicing file handling, byte manipulation, and validation in Python. By implementing this program, you will gain hands-on experience in handling file operations, byte manipulation, and validation 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

Binary File Reading (BMP Example)

 Objective

Develop a Python program that verifies if a BMP image file is valid by checking its header.

The program should read the file and confirm that the first two bytes match "B" and "M" (ASCII codes 0x42 and 0x4D). If they do, it indicates that the file is potentially a valid BMP image.

 Example Python Exercise

 Copy Python Code
def verify_bmp_header(file_name):
    """
    Verifies if the given file is a valid BMP image by checking its header.
    
    Parameters:
    file_name (str): The name of the file to check.
    
    Returns:
    bool: True if the file is a valid BMP, False otherwise.
    """
    try:
        with open(file_name, 'rb') as file:
            # Read the first two bytes of the file
            header = file.read(2)
            
            # Check if the first two bytes match 'B' and 'M' (0x42 and 0x4D)
            if header == b'BM':
                return True
            else:
                return False
            
    except FileNotFoundError:
        print(f"The file '{file_name}' was not found.")
        return False
    except Exception as e:
        print(f"An error occurred: {e}")
        return False

# Main program execution
if __name__ == "__main__":
    # Ask the user to input the file name
    file_name = input("Please enter the BMP file name to verify: ")
    
    # Verify if the file is a valid BMP image
    if verify_bmp_header(file_name):
        print(f"The file '{file_name}' is a valid BMP image.")
    else:
        print(f"The file '{file_name}' is not a valid BMP image.")

 Output

Assume you have a BMP file named image.bmp. When you run the program, it will behave as follows:

Please enter the BMP file name to verify: image.bmp
The file 'image.bmp' is a valid BMP image.

If the file is not a BMP or the header does not match "BM", the program will output:

Please enter the BMP file name to verify: image.jpg
The file 'image.jpg' is not a valid BMP image.

If the file does not exist, it will output:

Please enter the BMP file name to verify: nonexistent.bmp
The file 'nonexistent.bmp' was not found.

 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.

  •  Saving Data to a Binary File

    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 inform...

  •  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...