Make a complete list of os.listdir () objects

Consider the following code snippet:

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

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

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

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

+6
source share
3 answers
 files = sorted(os.listdir('dumps'), key=lambda fn:os.path.getctime(os.path.join('dumps', fn))) 
+4
source

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) 
+10
source
 files = sorted([os.path.join('dumps', file) for file in os.listdir('dumps')], key=os.path.getctime) 
+3
source

Source: https://habr.com/ru/post/974795/


All Articles