Python program to Reverse a single line of a text file

Given a text file. The task is to reverse a single line of user’s choice from a given text file and update the already existing file.

Examples:

Input:
        Hello Geeks
        for geeks!

  User choice = 1

Output:
        Hello Geeks
        geeks! for

Input:
        This is a geek
        Welcome to GeeksforGeeks
        GeeksforGeeks is a computer science portal

    User choice = 0

Output:
        geek a is This
        Welcome to GeeksforGeeks
        GeeksforGeeks is a computer science portal

Implementation:



Let’s suppose the text file looks like this –

python-reverse-text-file

filter_none

edit
close

play_arrow

link
brightness_4
code

# Open file in read mode
f = open('GFG.txt', 'r')
  
# Read the content of the
# file and store it in a list
lines = f.readlines()
      
# Close file
f.close()
  
# User's choice
choice = 1
  
# Split the line into words 
line = lines[choice].split()
  
# line is reversed
Reversed = " ".join(line[::-1])
  
# Updating the content of the
# file
lines.pop(choice)
lines.insert(choice, Reversed)
  
# Open file in write mode
u = open('GFG.txt', 'w')
  
# Write the new content in file
# and note, it is overwritten 
u.writelines(lines)
u.close()

chevron_right


Output:

python-reverse-text-file1

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.