Printing the output in numerical order in python

Viewed 102

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?

3 Answers

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

Perhaps you just need to sort the filenames:

filename_last_lines = [[(filename, subprocess.check_output(['tail', '-1', path + 
    filename]))] for filename in sorted([f for f in listdir(path) if isfile(join(path, f)) and 
    f.endswith('.txt')])]

You will have to sort the list with a custom key function.

filename_last_lines.sort(key=lambda x: int(x[0][6:-4]))

Let's decode what the lambda does.

Every element of the list is a tuple, so x[0] grabs the first element of the tuple, the filename.

Then we want to extract the number from the filename as an integer, so:

In [1]: x = ('coord_70.txt', 1)
Out[1]: ('coord_70.txt', 1)

In [2]: int(x[0][6:-4])
Out[2]: 70
Related