Exercise
Reverse The Contents Of A Text File
Objective
Develop a Python program that inverts the contents of a text file. The program should create a new file with the same name but ending in ".tnv". This new file will contain the lines from the original file in reverse order, so the first line of the original file becomes the last, the second line becomes the second-to-last, and so on, with the last line in the original file becoming the first line in the new file.
Hint: A straightforward approach would be to read the file twice: the first read to count the number of lines, and the second read to load the lines into a list before writing them back in reverse order.
Example Python Exercise
Show Python Code
def invert_file_content(input_file):
"""
Inverts the content of a text file by reversing the order of its lines
and saves the reversed content into a new file with the extension '.tnv'.
Parameters:
input_file (str): The name of the input text file to read.
"""
# Generate the output file name by appending '.tnv' to the input file name
output_file = input_file.rsplit('.', 1)[0] + '.tnv'
try:
# Open the input file for reading
with open(input_file, 'r') as file:
lines = file.readlines() # Read all lines into a list
# Reverse the order of the lines
reversed_lines = lines[::-1]
# Open the output file for writing
with open(output_file, 'w') as file:
file.writelines(reversed_lines) # Write the reversed lines to the new file
print(f"Content successfully reversed and saved to {output_file}")
except FileNotFoundError:
print(f"Error: The file '{input_file}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Main program execution
if __name__ == "__main__":
input_file = input("Enter the name of the text file to invert (with extension, e.g., file.txt): ")
invert_file_content(input_file)
Output
User Input:
Enter the name of the text file to invert (with extension, e.g., file.txt): example.txt
Program Output After Inverting:
Content successfully reversed and saved to example.tnv
How It Works:
If the input file example.txt contains the following lines:
Line 1
Line 2
Line 3
Line 4
The program will create a new file called example.tnv with the reversed content:
Line 4
Line 3
Line 2
Line 1
Share this Python Exercise