首页 > 解决方案 > 导入 txt 文件并将行反转作为输出

问题描述

我是 python 新手,想知道如何设置一个函数来接受文件作为参数,但输出应该会产生它 inn 反转行

例如,如果文本文件包含以下内容:

"Jack and Jill went up the hill
to fetch a pail of water
jack fell down and broke his crown"

输出应该是

"to fetch a pail of water
jack fell down and broke his crown 
Jack and Jill went up the hill"

标签: pythonpython-3.x

解决方案


代码

with open('test.txt', 'r') as fr, open('test_out.txt', 'w') as fw:
    content = fr.readlines()
    for item in content[::-1]:
        fw.write("%s\n" % item.rstrip('\n'))

输入文件

Jack and Jill went up the hill
to fetch a pail of water
jack fell down and broke his crown

输出文件

jack fell down and broke his crown
to fetch a pail of water
Jack and Jill went up the hill

推荐阅读