JaAnTr JaAnTr - 1 year ago 113
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 = open("newtext.txt", "wb")

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 Source
f = open("text.txt", "rb")
s = f.readlines()
f = open("newtext.txt", "wb")
for item in s:
  print>>f, item
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download