Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort by mtime a given list of files in Python3?

I am trying to do a function which receives a list of files (absolute paths) and returns the list sorted by the mtime of the files. Note that the argument is a list of files, not a directory path.

Anyone can help me? Thank you in advance.

EDIT

import os

lista = []
path = 'my/custom/path/'
for dirname, dirnames, filenames in os.walk(path):
    for file in filenames:
        filepath = os.path.realpath(os.path.join(dirname, file))
        lista.append(filepath)

This way I get the list (every file in the path and subpaths), now I need to sort it by mtime!

like image 448
forvas Avatar asked Sep 30 '25 09:09

forvas


1 Answers

all you want is:

sorted_list = sorted(lista, key=lambda f: os.stat(f).st_mtime)

which will give you the list of files sorted by mtime.

like image 152
zmo Avatar answered Oct 02 '25 04:10

zmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!