Printing the output in numerical order in python

accidental_coder :

I have written a program which reads the last line of multiple files at once and prints the output as a list of tuples.

    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)

The output that I now get is (coord_70.txt, P), (coord_4.txt, R) and so on which is very random. I need to print this in numerical order as in (coord_1.txt, R), (coord_2.txt, R) and so on. Can you please suggest me changes to this code?

scenox :

Just apply sorted() on listdir:

    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')]]

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=408065&siteId=1