Python Forum

Full Version: Filer and sort files by modification time in a directory
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Greetings!
I need to filter files by file names, sort by the last modification time and process them.
I got this code but it does not work.
import glob, os
pt = "C:/PS_Power-Shell_scripts/Files/File.*"
all_files = glob.glob(pt)
all_files.sort(key=lambda x: x[1], reverse=True)
for file in all_files :
    print(f" -- {file}")


Could you help me with this?
Thank you.
Try
all_files.sort(key=lambda x: os.path.getmtime(x), reverse=True)
(May-02-2024, 03:57 AM)tester_V Wrote: [ -> ]I got this code but it does not work
This always amazes me. How do you guys get this code from? Does it fall from the sky? Don't you understand what the code does?
I would not lie, I Googled it and I do not understand it. I actually come up with a "readable' one and it works.
I'm not sure if it is a good code or not. Sorry about that!
lst_ogs = []

for item in Path(host_path).iterdir() :
	if item.is_file() :
		fname = Path(item).name
		#print(f" .. {fname}")
		if fname.startswith("some_log") : 
			lst_ogs.append(item)            

lst_ogs.sort(key=os.path.getmtime,reverse=True) 
Thank you!
(May-02-2024, 06:02 AM)tester_V Wrote: [ -> ]I Googled it and I do not understand it
I think it is OK to google but take the time to understand what the code does and why it does not work when it does not work. This way you can improve your Python skills.
Maybe this will help with the understanding part?

from pathlib import Path
import os

mydir = Path('/home/pedro/tmp/')
# get all files
filelist = [filename for filename in mydir.iterdir() if filename.is_file()]
# copy filelist
old_list = filelist.copy()
# sort filelist according to os.path.getmtime
filelist.sort(key=os.path.getmtime, reverse=True)
# compare the 2 lists
for f in range(len(filelist)):
    print(filelist[f])
    print(old_list[f])
To get the actual date of modification:

from datetime import datetime

def modification_date(filename):
    secs = os.path.getmtime(filename) # like: 1634870901.972196
    dt = datetime.fromtimestamp(secs)
    date = dt.strftime("%A %B %Y %H:%M:%S.%f")
    print(f'file is: {f}')
    print(f'last modified time in epoch seconds: {secs}')
    print(f'date of last modification was: {date}\n')

mydir = Path('/home/pedro/tmp/')
file_gen = (filename for filename in mydir.iterdir() if filename.is_file())
for f in file_gen:
    modification_date(f)
Thank you all for sharing the codes and coaching! You guys(girls?) are great!