Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make os.listdir() list complete paths

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?

like image 615
Sohaib Avatar asked Sep 04 '14 05:09

Sohaib


People also ask

How do you get full path from Listdir?

Use os.path. join() to the os. listdir() function! We'll make a function for this, which simply gets the full path, and returns a list of all such names.

What does os Listdir () do?

listdir() method in python is used to get the list of all files and directories in the specified directory. If we don't specify any directory, then list of files and directories in the current working directory will be returned.

Does os Listdir return a list?

Description. Python method listdir() returns a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.

How do I list the path of a file in Python?

Use isfile() function path. isfile('path') function to check whether the current path is a file or directory. If it is a file, then add it to a list. This function returns True if a given path is a file.


2 Answers

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)
like image 50
shx2 Avatar answered Sep 23 '22 09:09

shx2


files = sorted(os.listdir('dumps'), key=lambda fn:os.path.getctime(os.path.join('dumps', fn)))
like image 41
Steven Rumbalski Avatar answered Sep 20 '22 09:09

Steven Rumbalski