首页 > 解决方案 > 从txt文件中获取最后10行并排序

问题描述

我从 TXT 文件中得到最后 10 行,如下所示:

a_file = open("log.txt", "r")
lines = a_file.readlines()
last_lines = lines[-10:]

得到这样的答案:

c
d
e
f
g

如何对结果进行排序以使最后一行位于顶部?

g
f
e
d
c

标签: pythonsorting

解决方案


使用 reversed() 逐行向后读取文件:

a_file = open("log.txt", "r")
lines = a_file.readlines()
for line in reversed(lines):
    print(line)

推荐阅读