Finding most recently edited file in python

后端 未结 8 2100
说谎
说谎 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: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)
    

提交回复
热议问题