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.
-
3Concatenate a new line when writing to file: outfile.write(line.rstrip() + '\r')Abbas– Abbas04/25/2013 06:30:03Commented Apr 25, 2013 at 6:30
-
oh wow how did i miss that.. thankyou very much!James Pinson– James Pinson04/25/2013 06:33:58Commented Apr 25, 2013 at 6:33
4 Answers 4
One line will do:
open("out", "wb").writelines(reversed(open("in").readlines()))
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()))
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)
....
-
The last line in the file might not have a newlinejamylak– jamylak04/25/2013 06:38:06Commented Apr 25, 2013 at 6:38
-
Good catch. Pesky assumptions. :) Personally, I think I'd deal with that situation directly, rather than strip and replace every newline that exists.Travis Griggs– Travis Griggs04/25/2013 06:41:58Commented Apr 25, 2013 at 6:41
-
I thought about that but I decided it was more practical for me to just have the one liner instead of having to check 1. you have more than 0 lines and 2. the last line has a new linejamylak– jamylak04/25/2013 06:43:13Commented Apr 25, 2013 at 6:43
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()))