2013-04-25 127 views
1

我想要做的是从一个文本文档中取一系列行,并在一秒钟内将它们反过来。例如文本文档中包含:如何在Python中以相反的顺序将输入文件中的行写入输出文件3

hi 
there 
people 

因此,因此我希望写这些同样的思路,以文本文档B,只是这样的:

people 
there 
hi 

到目前为止,我有:

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() 

但这只返回:

peopletherehi 

在一行中。任何帮助,将不胜感激。

+3

连接一个新的行写入文件时:outfile.write(line.rstrip()+ '\ r') – Abbas 2013-04-25 06:30:03

+0

哇哦我怎么会错过..三江源非常感谢! – 2013-04-25 06:33:58

回答

2

为什么在写作之前你的行是rstrip()?当你写下每行的结尾处时,你正在剥离换行符。然而你却注意到你没有任何换行符。只需在写入中删除rstrip()。

少即是多。

更新

如果我不能证明/验证,最后一行具有终止新行,我个人倾向于乱用一条线在那里要紧,前场。例如。

.... 
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) 
.... 
+0

该文件的最后一行可能没有换行符 – jamylak 2013-04-25 06:38:06

+0

好的结果。 Pesky的假设。 :)就我个人而言,我认为我会直接处理这种情况,而不是去掉每一个存在的换行符。 – 2013-04-25 06:41:58

+0

我想过这个,但我决定对我来说更实际一点就是拥有一个班轮,而不必检查1.你有超过0行和2.最后一行有一个新行 – jamylak 2013-04-25 06:43:13

3

你只需要+ '\n'因为.write不会为你做的,你也可以用

print >>f, line.rstrip() 

等效在Python 3:

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

这将增加一个新行为你。或做这样的事情:

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

此代码假定你不这样做,知道最后有一个换行符与否,如果你知道它确实你可以使用

fout.writelines(reversed(fin.readlines())) 
0
with open(your_filename) as h: 
    print ''.join(reversed(h.readlines())) 

,或者,如果你想将它写入其他数据流:

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())) 
3

一个行会这样做:

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