Working with binary GIF files - Python Programming Exercise

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

Working With Binary GIF Files

 Objective

Develop a Python program to validate the structure of a GIF image file.

The program should check if the initial four bytes are G, I, F, and 8.

If the file appears to be correct, the program should also identify the GIF version (either 87 or 89), by inspecting the byte following these four, to determine if it is a 7 or a 9.

 Example Python Exercise

 Copy Python Code
def validate_gif(file_name):
    """
    Validates the structure of a GIF file by checking the first four bytes
    and identifying the GIF version (87 or 89).
    
    Parameters:
    file_name (str): The name of the GIF file to validate.
    """
    try:
        # Open the file in binary mode to read the first few bytes
        with open(file_name, 'rb') as file:
            # Read the first 6 bytes
            header = file.read(6)
            
            if len(header) < 6:
                print("Error: The file is too small to be a valid GIF image.")
                return
            
            # Check if the first four bytes are 'G', 'I', 'F', and '8'
            if header[:4] == b'GIF8':
                # Check the 5th byte to determine the GIF version
                version = header[4:5]
                
                if version == b'7':
                    print("The file is a valid GIF87a image.")
                elif version == b'9':
                    print("The file is a valid GIF89a image.")
                else:
                    print("Error: Invalid version detected in GIF file.")
            else:
                print("Error: The file is not a valid GIF image (incorrect header).")
    
    except FileNotFoundError:
        print(f"Error: 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 = input("Enter the name of the GIF file to validate (with extension, e.g., image.gif): ")
    validate_gif(file_name)

 Output

User Input:

Enter the name of the GIF file to validate (with extension, e.g., image.gif): example.gif
Program Output:

If the file is a valid GIF87a image:

The file is a valid GIF87a image.

If the file is a valid GIF89a image:

The file is a valid GIF89a image.
If the file has an incorrect header or version:

Error: The file is not a valid GIF image (incorrect header).
If the file is too small:

Error: The file is too small to be a valid GIF image.

 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.

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

  •  File Encryption Tool

    In this exercise, you will develop a Python program to encode the content of a text file into a new file, transforming the text in a way that it is not easily readabl...

  •  Word Counter

    In this exercise, you will develop a Python program to count the total number of words in a given text file. This exercise is perfect for practicing file handl...