Python program to Reverse a single line of a text file

Python program to Reverse a single line of a text file

In this tutorial, we'll learn how to reverse a specific line of a text file using Python.

Scenario: Let's assume we have a text file named sample.txt with the following content:

Hello World Python is awesome Iditect creates cool tools Have a nice day 

If we want to reverse the third line, the file should be updated to:

Hello World Python is awesome loot looc setaerc IAnepO Have a nice day 

Steps:

  1. Open the file in reading mode and read all lines into a list.
  2. Reverse the characters of the specified line in the list.
  3. Open the file in write mode and write the lines back to the file.

Python Code:

def reverse_line_of_file(filename, line_number): """ Reverses a specific line in a text file. :param filename: Name of the file to modify. :param line_number: The line number to reverse (0-indexed). """ with open(filename, 'r') as file: lines = file.readlines() # Reverse the specified line lines[line_number] = lines[line_number][::-1] with open(filename, 'w') as file: file.writelines(lines) # Example usage: filename = "sample.txt" line_number_to_reverse = 2 # third line (0-indexed) reverse_line_of_file(filename, line_number_to_reverse) 

Explanation:

  • We define the function reverse_line_of_file that takes in a filename filename and a line number line_number.
  • Using a context manager (with statement), we open the file in reading mode and read all the lines into a list named lines.
  • We then reverse the characters of the specified line using slicing with [::-1].
  • We again use a context manager to open the file in writing mode, which will overwrite the original content, and write the modified lines back to the file.
  • In the example usage, we call the reverse_line_of_file function with our sample filename and the line number we wish to reverse.

By using this method, we can easily reverse any line in a text file with minimal code. The approach can be extended to perform other modifications on specific lines of a file as needed.


More Tags

angular-router-guards actionresult jdbc-odbc spark-cassandra-connector postal-code progress-indicator rdlc cache-invalidation visualforce jxl

More Programming Guides

Other Guides

More Programming Examples