So far I have this code:
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?
If your input file is too big to fit in memory, here is an efficient way to reverse it:
Implementation:
The method
file.read()
returns a string of the whole file, not the lines.And since
s
is a string of the whole file, you're reversing the letters, not the lines!First, you'll have to split it to lines:
Or:
And your method, it is already correct:
Hope this helps!
You have to work line by line.