Python Forum
Filer and sort files by modification time in a directory
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Filer and sort files by modification time in a directory
#1
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.
Reply
#2
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?
« We can solve any problem by introducing an extra level of indirection »
Reply
#3
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!
Reply
#4
(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.
« We can solve any problem by introducing an extra level of indirection »
Reply
#5
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)
tester_V likes this post
Reply
#6
It seems like there's an issue with your code. The sorting function is sorting the file names as strings, not by their last modification time. Here's a corrected version of your code:

python
Copy code
import glob, os
from pathlib import Path

pt = "C:/PS_Power-Shell_scripts/Files/File.*"
all_files = glob.glob(pt)
all_files.sort(key=lambda x: os.path.getmtime(x), reverse=True)

for file in all_files:
print(f" -- {file}")
tester_V likes this post
Reply
#7
Thank you all for sharing the codes and coaching! You guys(girls?) are great!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Loop through all files in a directory? Winfried 10 526 Apr-23-2024, 07:38 PM
Last Post: FortuneCoins
  uploading files from a ubuntu local directory to Minio storage container dchilambo 0 503 Dec-22-2023, 07:17 AM
Last Post: dchilambo
  Downloading time zone aware files, getting wrong files(by date))s tester_V 9 1,091 Jul-23-2023, 08:32 AM
Last Post: deanhystad
  change directory of save of python files akbarza 3 955 Jul-23-2023, 08:30 AM
Last Post: Gribouillis
  Using pyinstaller with .ui GUI files - No such file or directory error diver999 3 3,514 Jun-27-2023, 01:17 PM
Last Post: diver999
  Monitoring a Directory for new mkv and mp4 Files lastyle 3 1,692 May-07-2023, 12:33 PM
Last Post: deanhystad
  Read directory listing of files and parse out the highest number? cubangt 5 2,444 Sep-28-2022, 10:15 PM
Last Post: Larz60+
Photo a.sort() == b.sort() all the time 3lnyn0 1 1,347 Apr-19-2022, 06:50 PM
Last Post: Gribouillis
  How to save files in a separate directory Scordomaniac 3 2,042 Mar-16-2022, 10:17 AM
Last Post: Gribouillis
  Rename Multiple files in directory to remove special characters nyawadasi 9 6,515 Feb-16-2021, 09:49 PM
Last Post: BashBedlam

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020