首页 > 解决方案 > 在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) 等等。您能建议我更改此代码吗?

标签: pythonfor-loop

解决方案


只需在 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')]]

推荐阅读