How To Retrieve The Most Recent File From A Folder In Python
Solution 1:
Instead of
not os.path.isdir(x)
you should useos.path.isfile(x)
.filter
is deprecated; list comprehensions are preferred:filelist = [f for f in filelist if os.path.isfile(f)]
os.listdir
just gives you the names of the items in the directory, not full paths. To get full paths, you need to do something likeos.path.join('MYDIRECTORY', f)
.
So all fixed up it should look like:
import os
rootpath = 'MYDIRECTORY'
filelist = [os.path.join(rootpath, f) for f inos.listdir(rootpath)]
filelist = [f for f in filelist ifos.path.isfile(f)]
newest = max(filelist, key=lambda x: os.stat(x).st_mtime)
Solution 2:
os.listdir()
does not include the directory you are listing in the paths that are returned. So you either have to os.chdir("MYDIRECTORY")
into it before you call os.stat(x)
, or prepend the name of the directory like os.stat("MYDIRECTORY/" + x)
.
Or chdir
into it beforehand and use listdir
on the current directory like os.listdir(".")
.
Solution 3:
The problem is that os.listdir
returns file names, not paths. While it may seem that the next command (filtering on os.path.isdir
) works given just the name, you should note that isdir
returns False
when no object exists with that name.
What you need to do is combine the path with the file names:
import os
dirname = 'MYDIRECTORY'
filenames = os.listdir(dirname)
filepaths = [os.path.join(dirname, filename) for filename in filenames]
files = [f for f in filepaths ifnotos.path.isdir(f)]
newest = max(files, key=lambda x: os.stat(x).st_mtime)
Note that I replaced the filter call with a list comprehension. This is considered more 'Pythonic' (eww), but I did it because list comprehensions are typically faster than filter/map in Python.
Post a Comment for "How To Retrieve The Most Recent File From A Folder In Python"