make os.listdir() list complete paths
Asked Answered
D

6

23

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?

Delubrum answered 4/9, 2014 at 5:11 Comment(0)
S
9
files = sorted(os.listdir('dumps'), key=lambda fn:os.path.getctime(os.path.join('dumps', fn)))
Sweven answered 4/9, 2014 at 5:23 Comment(0)
B
30

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)
Brasil answered 4/9, 2014 at 5:17 Comment(0)
S
9
files = sorted(os.listdir('dumps'), key=lambda fn:os.path.getctime(os.path.join('dumps', fn)))
Sweven answered 4/9, 2014 at 5:23 Comment(0)
H
5
files = sorted([os.path.join('dumps', file) for file in os.listdir('dumps')], key=os.path.getctime)
Hacker answered 1/7, 2017 at 19:35 Comment(0)
P
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.

Pincushion answered 27/5, 2022 at 17:2 Comment(0)
M
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']
Milissamilissent answered 27/5, 2022 at 17:43 Comment(0)
M
-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))
Mullah answered 27/10, 2021 at 23:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.