Saturday, November 16, 2024
Google search engine
HomeLanguagesPython program to Reverse a single line of a text file

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 Lazyroar!

  User choice = 1

Output:
        Hello Geeks
        Lazyroar! for

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

    User choice = 0

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

Implementation: Let’s suppose the text file looks like this – python-reverse-text-file 

Python3




# 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()


Output: python-reverse-text-file1

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.

RELATED ARTICLES

Most Popular

Recent Comments