Skip to main content
 首页 » 编程设计

python之如何在 python 3 中以相反的顺序将行从输入文件写入输出文件

2025年05月04日10langtianya

我想做的是从一个文本文档中取出一系列行,然后在一秒钟内将它们倒过来。例如文本文档 a 包含:

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  

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

请您参考如下方法:

一行就可以:

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