Dump - Python Programming Exercise

In this exercise, you will develop a Python program to create a "dump" utility: a hex viewer that displays the contents of a file, with 16 bytes in each row and 24 rows in each screen. This exercise is perfect for practicing file handling, byte manipulation, and string formatting in Python. By implementing this program, you will gain hands-on experience in handling file operations, byte manipulation, and string formatting 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

Dump

 Objective

Develop a Python program to create a "dump" utility: a hex viewer that displays the contents of a file, with 16 bytes in each row and 24 rows in each screen. The program should pause after displaying each screen before showing the next 24 rows.

In each row, the 16 bytes should be displayed first in hexadecimal format and then as characters. Bytes with an ASCII code less than 32 should be shown as a dot instead of the corresponding non-printable character.

You can search for "hex editor" on Google Images to see an example of the expected appearance.

 Example Python Exercise

 Copy Python Code
# Python program to create a hex viewer for files

def hex_viewer(file_path):
    try:
        # Open the file in binary read mode
        with open(file_path, 'rb') as file:
            # Row and screen counters
            row_count = 0
            screen_count = 0

            while True:
                # Read 16 bytes at a time
                chunk = file.read(16)

                # Break the loop if no more data is left
                if not chunk:
                    break

                # Display the offset (row start position)
                print(f"{row_count * 16:08X}: ", end="")

                # Display the chunk in hexadecimal format
                hex_representation = " ".join(f"{byte:02X}" for byte in chunk)
                print(f"{hex_representation:<48}", end=" ")

                # Display the chunk as ASCII characters
                ascii_representation = "".join(
                    chr(byte) if 32 <= byte <= 126 else "." for byte in chunk
                )
                print(ascii_representation)

                # Increment row count
                row_count += 1

                # Pause after displaying 24 rows (one screen)
                if row_count % 24 == 0:
                    screen_count += 1
                    input(f"-- Screen {screen_count} (Press Enter to continue) --")

            # Final message after the dump is complete
            print("-- End of file --")

    except FileNotFoundError:
        print(f"Error: The file '{file_path}' was not found.")
    except Exception as e:
        print(f"Error: {str(e)}")


# Example usage
hex_viewer("example_file.bin")

 Output

Example Input File (example_file.bin):

Binary content (can be any type of file):

Hello, World! This is a test file.
1234567890abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()

Example Output:

00000000: 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 20 54 68  Hello, World! Th
00000010: 69 73 20 69 73 20 61 20 74 65 73 74 20 66 69 6C  is is a test fil
00000020: 65 2E 0A 31 32 33 34 35 36 37 38 39 30 61 62 63  e..1234567890abc
00000030: 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 72 73  defghijklmnopqrs
00000040: 74 75 76 77 78 79 7A 0A 41 42 43 44 45 46 47 48  tuvwxyz.ABCDEFGH
00000050: 49 4A 4B 4C 4D 4E 4F 50 51 52 53 54 55 56 57 58  IJKLMNOPQRSTUVWX
00000060: 59 5A 21 40 23 24 25 5E 26 2A 28 29              YZ!@#$%^&*()
-- Screen 1 (Press Enter to continue) --
-- End of file --

 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.

  •  Text Filter

    In this exercise, you will develop a Python program to create a utility that censors text files. This exercise is perfect for practicing file handling, string ...

  •  SQL to Plain Text

    In this exercise, you will develop a Python program to parse SQL INSERT commands and extract their data into separate lines of text. This exercise is perfect f...

  •  PGM Image Viewer

    In this exercise, you will develop a Python program to create a utility that reads and displays images in the PGM format, which is a version of the NetPBM image forma...

  •  Console BMP Viewer V2

    In this exercise, you will develop a Python program to create a utility that displays a 72x24 BMP file on the console. This exercise is perfect for practicing ...

  •  Saving Data to a Text File

    In this exercise, you will develop a Python program to collect multiple sentences from the user (continuing until the user presses Enter without typing anything) and ...

  •  Adding Content to a Text File

    In this exercise, you will develop a Python program that prompts the user to input multiple sentences, stopping when they press Enter without typing anything. This ...