Reverse the contents of a text file - Python Programming Exercise

In this exercise, you will develop a Python program that inverts the contents of a text file. This exercise is perfect for practicing file handling, loops, and string manipulation in Python. By implementing this program, you will gain hands-on experience in handling file operations, loops, and string manipulation 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

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

 Copy 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

 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.

  •  Working with binary GIF files

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

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