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 –
Python3
f = open ( 'GFG.txt' , 'r' )
lines = f.readlines()
f.close()
choice = 1
line = lines[choice].split()
Reversed = " ".join(line[:: - 1 ])
lines.pop(choice)
lines.insert(choice, Reversed )
u = open ( 'GFG.txt' , 'w' )
u.writelines(lines)
u.close()
|
Output:
Time complexity: O(n), where n is the number of lines in the file.
Auxiliary space: O(n), where n is the number of lines in the file.
Last Updated :
20 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...