make os.listdir() list complete paths

Sohaib picture Sohaib · Sep 4, 2014 · Viewed 19.1k times · Source

Consider the following piece of code:

files = sorted(os.listdir('dumps'), key=os.path.getctime)

The objective is to sort the listed files based on the creation time. However since the the os.listdir gives only the filename and not the absolute path the key ie, the os.path.getctime throws an exception saying

OSError: [Errno 2] No such file or directory: 'very_important_file.txt'

Is there a workaround to this situation or do I need to write my own sort function?

Answer

shx2 picture shx2 · Sep 4, 2014

You can use glob.

import os
from glob import glob
glob_pattern = os.path.join('dumps', '*')
files = sorted(glob(glob_pattern), key=os.path.getctime)