The task is to reverse the single line of text of the given text file and update it in the same file.
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()
- 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.