Python 我想反转以下代码输出的格式(行和行号都应该是相反的顺序)

Python 我想反转以下代码输出的格式(行和行号都应该是相反的顺序),python,Python,输出: def ls(): with open("todo.txt",'r+') as file: lines = file.readlines() # lines = reversed(lines) for num,line in enumerate(lines): print(num,line) 预期产出: 0 Lemon 1 StarFruit 2 Banana

输出:

def ls():
    with open("todo.txt",'r+') as file:
        lines = file.readlines()
#       lines = reversed(lines)
        for num,line in enumerate(lines):
            print(num,line)
预期产出:

0 Lemon
    
1 StarFruit
    
2 Banana
    
3 Apple
    
4 Grapes
使用reversed()向后逐行读取文件
将呼叫放回
已反转的
。这是正确的。然后更改最后一行以实际打印所需的数字:
print(len(lines)-num,line)
。它会产生TypeError:。
list\u reverseiterrator
类型的对象没有len()啊,对不起,是Python 2遗留的习惯。使用
len(列出(行))
。我还需要行号(降序)
5 Grapes
    
4 Apple
    
3 Banana
    
2 Starfruit
    
1 Lemon
textfile = open("todo.txt")
lines = textfile.readlines()
for line in reversed(lines):
    print(line)