Wilgens Metelus
Wilgens Metelus

Reputation: 25

Reversing a list in a text file

This program is meant to read one file, and then create another file with the list in reverse. The first file reads

Luke 19
Anakin 45
Han 35
Leia 19
Obiwan 70
Yoda 400

The 2nd file should be this list in reverse, with Yoda 400 first then Luke 19 last. I am getting an error with the program with using the reverse() function and it says that the object has no attribute "reverse".
Edit: Suggested post doesn't create a new file with the list in reverse, it just prints it again in reverse.

f = open("file1.txt","r")
f1 = open("file2.txt","w")
f1.write(f.reverse())

Upvotes: 0

Views: 1996

Answers (2)

AkhilKrishnan
AkhilKrishnan

Reputation: 534

You can follow this code,

f = open("file1.txt","r")
f1 = open("file2.txt","w")
f1.writelines(reversed(f.readlines()))
fout = open("file2.txt",'r')
fout.read()

Upvotes: 1

Deepstop
Deepstop

Reputation: 3817

This works, although there is one gotcha, which is that in some files the last line has no eol character, which means that first line in the new file won't have one either.

with open("file1.txt","r") as f1:
    lines = f1.readlines()

with open('file2.txt', 'w') as f2:
    for item in reversed(lines):
        f2.write(f"{item}")

If the last line is a problem, then you could remove and replace the newline characters.

with open("file1.txt","r") as f1:
    lines = f1.read().splitlines()

lines.reverse()

with open('file2.txt', 'w') as f2:
        f2.write('\n'.join(lines))

Upvotes: 1

Related Questions