3

我试过搜索,但我没有找到我需要的东西。我正在使用 python 3,我需要帮助以相反的顺序将文本文件写入不同的输出文件。

所以这将是输入文件

Hey, I am Fred

Fred, what's up

Fred fred fred

这将是输出文件

Fred fred fred

Fred, what's up

Hey, I am Fred

如果有人对如何完成有任何见解,我将不胜感激,

4

1 回答 1

2
with open (input_file_name) as fi, open(output_file_name, 'w') as fo:
    fo.writelines(reversed(fi.readlines()))

如果 input_file 格式错误(最后一行不以 '\n' 结尾),您可以使用快速(可能不太有效)的 hack:

with open ('c:\\temp\\input_file') as fi, open('c:\\temp\\output_file', 'w') as fo:
    fo.write('\n'.join(reversed(fi.read().splitlines())))
于 2012-11-04T09:41:32.493 回答