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
#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


Messages In This Thread
RE: Filer and sort files by modification time in a directory - by Pedroski55 - May-02-2024, 07:59 AM

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