Home > Net >  Is there an easy way to have the file names and their last modified dates listed?
Is there an easy way to have the file names and their last modified dates listed?

Time:02-03

I´m actually trying to list (filename and their last modified date) within a directory: But when I run my command, I´m actually having just the list of the files but with the modified dates all similar. Can someone help identify the problem in my script?

CodePudding user response:

It seems like you forgot to attach your script, but these few lines do the job (python 3):

import os
from datetime import datetime

search_dir = "/example/path"
os.chdir(search_dir)
files = filter(os.path.isfile, os.listdir(search_dir)) #filter just files, no directories
paths = [os.path.join(search_dir, f) for f in files] # path for each file
fileNames = [os.path.basename(x) for x in paths] # list of file names
dates = [os.path.getmtime(x) for x in paths] # list of modification dates

filesDates = list(zip(fileNames, dates)) # zip names and dates
filesDates.sort(key = lambda x: x[1]) # sort by dates

for x in filesDates: # print, converting timestamp to human readable format
    print(x[0], ' modified: ', datetime.fromtimestamp(x[1], tz=None))

example output:

talsh_En_T2.F90  modified:  2023-01-19 11:31:59.768919
tenpi.py  modified:  2023-01-26 16:33:28.003705
test.py  modified:  2023-02-02 11:56:24.067713
  • Related