eb1239
eb1239

Reputation: 15

Write a program that reads a file and writes out a new file with the lines in reversed order

Write a program that reads a file and writes out a new file with the lines in reversed order (i.e. the first line in the old file becomes the last one in the new file.)

I am able to reverse the lines correctly using reverse() but I cannot get it to write the output to a new file. Here is the code that I have so far.

f = open("States.txt", "rb")
s = f.readlines()
f.close()
f = open("newstates2.txt", "wb")
x = s.reverse()
f.write(x)

Upvotes: 1

Views: 2807

Answers (2)

MarkS
MarkS

Reputation: 1539

file = "<path to file>"
with open(file) as f:
    lines = f.readlines()

reverse_file = "e:\\python\\reversed.txt"
with open(reverse_file, 'w') as rev:
    rev.writelines(lines[::-1])

Upvotes: 1

Daniel Giger
Daniel Giger

Reputation: 2543

reverse() doesn't return anything. If you want to use reverse(), you have to use s afterward instead of making a new variable for the reversed list. Also, readlines() returns a list, so you can't call write() on it directly, but you can iterate through it. Here's an updated version:

f = open("States.txt", "rb")
s = f.readlines()
f.close()
f = open("newstates2.txt", "wb")
s.reverse()
for line in s:
    f.write(line)
f.close()

Alternatively, you could use reversed() which does return the reversed version:

for line in reversed(s):
    f.write(line)

Upvotes: 1

Related Questions