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?
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.
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.
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 '.
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.
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)
files = sorted(os.listdir('dumps'), key=lambda fn:os.path.getctime(os.path.join('dumps', fn)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With