Exercise
Reversing File Content
Objective
Develop a Python program to "invert" a file: create a new file with the same name but ending in ".inv" and store the bytes from the original file in reverse order. In the resulting file, the first byte will become the last, the second byte will become the second-to-last, and so on. The final byte in the original file should appear first in the new file.
You will only need to submit the Python file, with a comment including your name.
Hint: To determine the length of a binary file (using `BinaryReader`), you can check the file's length using `myFile.BaseStream.Length`. Additionally, to move to a different position in the file, you can use `myFile.BaseStream.Seek(4, SeekOrigin.Current)`.
The position options available for seeking are: `SeekOrigin.Begin`, `SeekOrigin.Current`, or `SeekOrigin.End`.
Example Python Exercise
Show Python Code
# This program reads a file, reverses the byte order, and writes the reversed content into a new file with ".inv" extension.
def invert_file(input_filename):
try:
# Open the input file in binary read mode
with open(input_filename, 'rb') as infile:
# Read the entire content of the file
content = infile.read()
# Reverse the byte order of the content
reversed_content = content[::-1]
# Create the new file name by adding ".inv" extension
output_filename = input_filename + ".inv"
# Open the output file in binary write mode
with open(output_filename, 'wb') as outfile:
# Write the reversed content to the new file
outfile.write(reversed_content)
print(f"File has been successfully inverted and saved as {output_filename}.")
except FileNotFoundError:
print(f"The file {input_filename} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
input_file = "example.txt" # Replace with your input file name
invert_file(input_file)
Output
If the example.txt file contains:
Hello, this is a test file!
After running the program, the example.txt.inv file will contain:
!elfi tset a si siht ,olleH
Share this Python Exercise