21

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?

Nilesh
  • 20,521
  • 16
  • 92
  • 148
Sohaib
  • 4,556
  • 8
  • 40
  • 68

6 Answers6

29

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)
shx2
  • 61,779
  • 13
  • 130
  • 153
9
files = sorted(os.listdir('dumps'), key=lambda fn:os.path.getctime(os.path.join('dumps', fn)))
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
5
files = sorted([os.path.join('dumps', file) for file in os.listdir('dumps')], key=os.path.getctime)
Maboroshy
  • 51
  • 1
  • 2
1

Getting a list of absolute paths for all files in a directory using pathlib in python3.9 on Windows

from pathlib import Path

# directory name is 'dumps'

[str(child.resolve()) for child in Path.iterdir(Path('dumps'))]

Path.iterdir() takes in a pathlib object, and so we do Path(dir) to get that object. It then spits out each file as the child, but as a relative path. child.resolve() gives the absolute path, but again as a pathlib object, so we do str() on it to return a list of strings.

scotscotmcc
  • 2,719
  • 1
  • 6
  • 29
1

You can also use os.path.join with os.path.abspath, combined with map and lambda in Python.

>>>list(map(lambda x: os.path.join(os.path.abspath('mydir'), x),os.listdir('mydir')))

This will join the absolute path of mydir with os.listdir('mydir'). The output:

['/home/ahmad/Desktop/RedBuffer/Testdata/testing.avi',
'/home/ahmad/Desktop/RedBuffer/Testdata/testing2.avi', 
'/home/ahmad/Desktop/RedBuffer/Testdata/text_changing.avi', 
'/home/ahmad/Desktop/RedBuffer/Testdata/text_static.avi', 
'/home/ahmad/Desktop/RedBuffer/Testdata/test_img.png']
Ahmad Anis
  • 2,322
  • 4
  • 25
  • 54
-2

Here is another solution resulting in an np array instead of list, if it works better for someone. Still uses os

import numpy as np
import os

NPFileListFullURL=np.char.add(Folder_Path, os.listdir(Folder_Path))