简体   繁体   中英

How to get the last 4 modified files in directory Python

I often need to parse through the logs of a messy application. This application has many instances so many logs for each instance. For each instance of this application, I need to search the newest 4 files in each log directory to look for files, how can I achieve this? I know how to get the latest file but I don't know how to make it count back 4 times:

list_of_files = glob.glob('D:\logs\Worker1\*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getmtime)

You're very close:

list_of_files = glob.glob(r'D:\logs\Worker1\*')
list_of_files.sort(key=os.path.getmtime)
newest = list_of_files[-4:]

Why don't you get all the modified times, sort them in descending order, and pick the first 4?

Something like this:

files_modified_list = [(f, os.path.getmtime(f)) for f in list_of_files]
sorted_files_modified_list = sorted(file_modified_list, key=lambda x: x[1])
top_4_latest_files = [f[0] for f in sorted_files_modified_list[0:3]]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM