James Pinson
James Pinson

Reputation: 221

How to write lines from a input file to an output file in reversed order in python 3

What I want to do is take a series of lines from one text document, and put them in reverse in a second. For example text document a contains:

hi
there
people

So therefore I would want to write these same lines to text document b, except like this:

people
there
hi

So far I have:

def write_matching_lines(input_filename, output_filename):
    infile = open(input_filename)
    lines = infile.readlines()
    outfile = open(output_filename, 'w')
    for line in reversed(lines):
            outfile.write(line.rstrip())
    infile.close()
    outfile.close()

but this only returns:

peopletherehi 

in one line. any help would be appreciated.

Upvotes: 1

Views: 759

Answers (4)

jamylak
jamylak

Reputation: 133634

You just need to + '\n' since .write does not do that for you, alternatively you can use

print >>f, line.rstrip()

equivalently in Python 3:

print(line.rstrip(), file=f) 

which will add a new line for you. Or do something like this:

>>> with open('text.txt') as fin, open('out.txt', 'w') as fout:
        fout.writelines(reversed([line.rstrip() + '\n' for line in fin]))

This code assumes that you don't know if the last line has a newline or not, if you know it does you can just use

fout.writelines(reversed(fin.readlines()))

Upvotes: 3

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13196

One line will do:

open("out", "wb").writelines(reversed(open("in").readlines()))

Upvotes: 3

Jakub M.
Jakub M.

Reputation: 33857

with open(your_filename) as h:
    print ''.join(reversed(h.readlines()))

or, if you want to write it to other stream:

with open(your_filename_out, 'w') as h_out:
    with open(your_filename_in) as h_in:
        h_out.write(''.join(reversed(h_in.readlines()))

Upvotes: 0

Travis Griggs
Travis Griggs

Reputation: 22262

Why do you rstrip() your line before writing it? You're stripping off the newline at the end of each line as you write it. And yet you then notice that you don't have any newlines. Simply remove the rstrip() in your write.

Less is more.

Update

If I couldn't prove/verify that the last line has a terminating newline, I'd personally be inclined to mess with the one line where it mattered, up front. E.g.

....
outfile = open(output_filename, 'w')
lines[-1] = lines[-1].rstrip() + '\n' # make sure last line has a newline
for line in reversed(lines):
        outfile.write(line)
....

Upvotes: 2

Related Questions