![]() |
VOOZH | about |
Given a text file that contains multiple lines, the task is to reverse the words of only one line chosen by the user. All other lines in the file should remain unchanged. The line is selected using a 0-based index, which means:
For Example:
Input: Hello Geeks User choice = 0
for geeks!
Output: Geeks Hello
for geeks!
Explanation: selected line (Hello Geeks) is reversed word by word to become Geeks Hello.
Now, let's explore different methods to reverse a single line of a text file in python.
Below is the sample file (gfg.txt) used in this article:
This method loads the whole file into a list using readlines(), changes only the line at the selected index, and then writes everything back to the file.
Output
Explanation:
This method reads the file line-by-line and uses enumerate() to check the line number so only the chosen line is reversed.
Output
Explanation:
This method uses Pythonβs fileinput module to update a file line-by-line without loading the entire file into memory.
Output
Explanation: