f = open("text.txt", "rb") s = f.read() f.close() f = open("newtext.txt", "wb") f.write(s[::-1]) f.close() | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

f = open("text.txt", "rb") s = f.read() f.close() f = open("newtext.txt", "wb") f.write(s[::-1]) f.close()

The text in the original file is: This is Line 1 This is Line 2 This is Line 3 This is Line 4 And when it reverses it and saves it the new file looks like this: 4 eniL si sihT 3 eniL si sihT 2 eniL si sihT 1 eniL si sihT When I want it to look like this: This is line 4 This is line 3 This is line 2 This is line 1 How can I do this?

18th Oct 2017, 3:42 PM
Keerthana Vema
Keerthana Vema - avatar
1 Answer
+ 1
Assuming the input file actually consists of different lines (i.e., has newline characters), replace "f.read()" with "f.readlines()". If it's not actually lines and is how you have written it, then what I would do is make 's' a list containing each word from the input. I would then perform the necessary logic to concatenate each line (notice that even the numbers would be individual words, and each 'line' has 4 words, probably storing each line in a temporary variable). Then reverse the resulting list, and continue on (I apologise for no code since I'm currently not in a comfortable position to actually write the code).
18th Oct 2017, 4:08 PM
Aryaman Srivastav
Aryaman Srivastav - avatar