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 –

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




.png)