导入txt文件并将行反转为输出

时间:2018-11-27 14:40:07

标签: python python-3.x

我是python的新手,想知道如何设置一个函数来接受文件作为参数,但随后输出应在反相行中生成它

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

"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"

2 个答案:

答案 0 :(得分:1)

代码

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

答案 1 :(得分:0)

除了第一个解决方案之外,您还可以在此处使用reversed()

with open("example.txt") as fp, open("output.txt", mode="w") as fw:
    for line in reversed(fp.readlines()):
        fw.write(line.rstrip() + "\n")