JaAnTr JaAnTr - 3 months ago 13
Python Question

Read lines from a text file, reverse and save in a new text file

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?

Answer
f = open("text.txt", "rb")
s = f.readlines()
f.close()
f = open("newtext.txt", "wb")
s.reverse()
for item in s:
  print>>f, item
f.close()