I am trying to get the most recent file added to a directory using python 2.7 os
and glob
modules.
import os
import glob
path = "files/"
newestFile = max(glob.iglob(path + '*.txt'), key=os.path.getctime)
print newestFile
When I print the newestFile
variable I get the path included ie
files\\file.txt
I just want the filename
but my .txt
file and .py
script are not in the same directory. The text file is one directory down under the files directory. How do I refer to the directory and get the newest .txt
file added to that directory.
You can use os.path.basename
to just get the filename:
newestFile = os.path.basename(max(glob.iglob(path + '*.txt'), key=os.path.getctime))
os.path.getctime
is going to need the full path so one way or another you would have to use the full path.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.