python - 在python中按数字顺序打印输出
问题描述
我编写了一个程序,它一次读取多个文件的最后一行并将输出打印为元组列表。
from os import listdir
from os.path import isfile, join
import subprocess
path = "/home/abc/xyz/200/coord_b/"
filename_last_lines = [[(filename, subprocess.check_output(['tail', '-1', path +
filename]))] for filename in [f for f in listdir(path) if isfile(join(path, f)) and
f.endswith('.txt')]]
print(filename_last_lines)
我现在得到的输出是 (coord_70.txt, P), (coord_4.txt, R) 等等,这是非常随机的。我需要按数字顺序打印它,如 (coord_1.txt, R)、(coord_2.txt, R) 等等。您能建议我更改此代码吗?
解决方案
只需在 listdir 上应用 sorted():
filename_last_lines = [[(filename, subprocess.check_output(['tail', '-1', path +
filename]))] for filename in [f for f in sorted(listdir(path)) if isfile(join(path, f)) and
f.endswith('.txt')]]
推荐阅读
- python - 在 PIL 中将图像的尺寸更改为一半
- google-apps-script - 提交时触发脚本的 Google 表单始终无法正常工作
- c# - 取消从 Angular 到 .NET Core 的长操作
- c++ - std::shared_ptr operator= 更改对象,而不是指针值?
- python - 气流宏未转换为日期
- c# - Windows 窗体:根据列表选择显示唯一面板
- filter - PowerBI_filter IDs 专门包含列中的值
- docker - 是否可以从没有控制文件和系统表空间的单个数据文件中取回我的数据?
- ansible - ansible 中的 Gluster_Volume 模块
- javascript - 如何避免 docker-compose 中的“无效挂载路径”