Search for last edited file in python

I have a set of folders and I want to be able to run a function that will find the last edited file and tell me the file name and the folder in which it is located.

Folder Layout:

root Folder A File A File B Folder B File C File D etc... 

Any tips to help me get started when I came across a wall.

+8
python file path folder
source share
7 answers

You should look at os.walk as well as os.stat , which may allow you to do something like:

 import os max_mtime = 0 for dirname,subdirs,files in os.walk("."): for fname in files: full_path = os.path.join(dirname, fname) mtime = os.stat(full_path).st_mtime if mtime > max_mtime: max_mtime = mtime max_dir = dirname max_file = fname print max_dir, max_file 
+16
source share

This helps wrap the inline directory going to a function that gives only full file paths. Then you can simply take the function that returns all the files and select the one that has the longest modification time:

 import os def all_files_under(path): """Iterates through all files that are under the given path.""" for cur_path, dirnames, filenames in os.walk(path): for filename in filenames: yield os.path.join(cur_path, filename) latest_file = max(all_files_under('root'), key=os.path.getmtime) 
+6
source share
  • use os.walk to display files
  • use os.stat to get the modified timestamp file (st_mtime)
  • put both timestamps and file names in the list and sort them by timestamp, the largest timestamp is the last edited file.
+3
source share
+1
source share

Use os.path.walk() to navigate the directory tree and os.stat().st_mtime to get mtime files.

The function you pass to os.path.walk() (the visit parameter) just needs to keep track of the longest time that it looked through and where it saw it.

+1
source share

I use path = r"C:\Users\traveler\Desktop" :

 import os def all_files_under(path): #"""Iterates through all files that are under the given path.""" for cur_path, dirnames, filenames in os.walk(path): for filename in filenames: yield os.path.join(cur_path, filename) latest_file = max(all_files_under('root'), key=os.path.getmtime) 

What am I missing here?

0
source share

If someone is looking for a one-line way to do this:

 latest_edited_file = max([f for f in os.scandir("path\\to\\search")], key=lambda x: x.stat().st_mtime).name 
0
source share

All Articles