首页 > 解决方案 > 如何编写一个函数,反向打印 data.txt 中的行

问题描述

我花了几周的时间来正确学习 python,但不知道如何拆分lines[::-1]以获得所需的结果:

Order will return.
Reflect, repent, and reboot
Chaos reigns within.

Chaos reigns within. 
Reflect, repent, and reboot 
Order will return.

到目前为止,我所做的是以正确的顺序打印出 3 个句子,但其他一切都是错误的。

def print_reversed(filename):
    """prints out the lines from the file in reversed order"""
    filename = open(filename) 
    contents = filename.read()   
    lines = contents.splitlines()
    for line in lines:
        print(lines[::-1])  

print_reversed('data.txt')

到目前为止我所做的打印出来:

['Order will return.', 'Reflect, repent, and reboot ', 'Chaos reigns within. ']
['Order will return.', 'Reflect, repent, and reboot ', 'Chaos reigns within. ']
['Order will return.', 'Reflect, repent, and reboot ', 'Chaos reigns within. ']

帮助将不胜感激!

标签: python-3.xlistfile

解决方案


推荐阅读