Program to reverse the single line of text file and update the file accordingly using Python

Introduction

The task is to reverse the single line of text of the given text file and update it in the same file.

Program to reverse the single line of text file and update the file accordingly using Python

Program

readFile = open('contentFile.txt', 'r') 
row = readFile.readlines()  
readFile.close() 
selectRow = 0 
tmp = row[selectRow].split() 
strRev = " ".join(tmp[::-1]) 
row.pop(selectRow) 
row.insert(selectRow, strRev) 
writeFile = open('contentFile.txt', 'w')   
writeFile.writelines(row) 
writeFile.close()

Output

Program to reverse the single line of text file and update the file accordingly using Python Output

Explanation

Approach:

  • Open the content file in read mode and output file in write mode.
  • Split the line of text into words and store it into a variable. (Here we are reversing line 2)
  • Reverse the contents of the variable.
  • Pop the content of line 2.
  • Insert the reversed content at line 2.
  • Write the updated content in the output file.
  • Close files.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.