Finding most recently edited file in python

后端 未结 8 1926
说谎
说谎 2021-02-02 02:57

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

F

相关标签:
8条回答
  • 2021-02-02 03:15

    For multiple files, if anyone came here for that:

    import glob, os
    
    files = glob.glob("/target/directory/path/*/*.mp4")
    files.sort(key=os.path.getmtime)
    
    for file in files:
       print(file)
    

    This will print all files in any folder within /path/ that have the .mp4 extension, with the most recently modified file paths at the bottom.

    0 讨论(0)
  • 2021-02-02 03:23

    You should look at the os.walk function, as well as os.stat, which can let you 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
    
    0 讨论(0)
  • 2021-02-02 03:25

    It helps to wrap the built in directory walking to function that yields only full paths to files. Then you can just take the function that returns all files and pick out the one that has the highest 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)
    
    0 讨论(0)
  • 2021-02-02 03:30

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

    The function you pass to os.path.walk() (the visit parameter) just needs to keep track of the largest mtime it's seen and where it saw it.

    0 讨论(0)
  • 2021-02-02 03:33

    If anyone is looking for an one line way to do it:

    latest_edited_file = max([f for f in os.scandir("path\\to\\search")], key=lambda x: x.stat().st_mtime).name
    
    0 讨论(0)
  • 2021-02-02 03:35
    • use os.walk to list files
    • use os.stat to get file modified timestamp (st_mtime)
    • put both timestamps and filenames in a list and sort it by timestamp, largest timestamp is most recently edited file.
    0 讨论(0)
提交回复
热议问题