Exercise
Reverse Binary File V2
Objective
Develop a Python program to "reverse" a binary file using a "FileStream". The program should generate a new file with the same name, ending in ".inv", and store the bytes in reverse order. This means the last byte of the original file will become the first byte of the new file, the second-to-last byte will be the second byte, and so on, until the first byte of the original file, which will be the last byte in the new file.
Only the ".py" file is required, and it should include a comment with your name.
Example Python Exercise
Show Python Code
# This program reverses the bytes of a binary file and saves the result in a new file with the ".inv" extension.
def reverse_binary_file(input_filename):
try:
# Open the input binary file in read mode
with open(input_filename, 'rb') as input_file:
# Read the entire content of the binary file
file_content = input_file.read()
# Generate the output filename by adding ".inv" before the file extension
output_filename = input_filename.rsplit('.', 1)[0] + '.inv'
# Open the output binary file in write mode
with open(output_filename, 'wb') as output_file:
# Write the reversed content to the new file
output_file.write(file_content[::-1])
print(f"Reversed binary file created: {output_filename}")
except FileNotFoundError:
print("The specified file does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
input_file = "example.bin" # Replace with your binary file name
reverse_binary_file(input_file)
Output
Reversed binary file created: example.inv
Share this Python Exercise