Sep-18-2021, 01:36 PM
from __future__ import print_function from collections import namedtuple from datetime import datetime, timedelta from os import listdir from os.path import getmtime from os.path import join as joinpath Result = namedtuple("File", "file age") def calculate_days(td): # you can also round here or convert it to an int return td.total_seconds() / 3600 / 24 def get_mtime(file): return datetime.fromtimestamp(getmtime(file)) def find(root_path, file_pattern, min_age_days=1): min_age = timedelta(days=min_age_days) now = datetime.now() for file in listdir(root_path): if file_pattern in file: file = joinpath(root_path, file) mtime = get_mtime(file) delta = now - mtime if delta > min_age: # if unwanted, you can refactor this and remove the age from the Result # or just yield the file, which is a str yield Result(file, calculate_days(delta)) if __name__ == "__main__": for file in find("/home/deadeye/", ".py"): print(file.file) # accessing the Result, which is a namedtuple # print(file) will print the representation of the namedtuple with data # print(file.age) will show the age in days # but you can also use index access on a Result # print(file[0]) will print the first field, which is file # a namedtuple act as a tuple and supports argument unpacking for file, age in find("/home/deadeye/", ".py"): pass # file is a file # age is the age of the file # or to get a list: # files = list(find("/home/deadeye", ".py")) # print(files)Works with Python 2.7 and Python 3.x+
By the way, the order of files in a directory is defined by their inode number and not the creation date.
Some scientists expected that
os.path.listdir()
return the alphabetical order, which is not right.If the alphabetical order is required, you can wrap sorted around
listdir
.Before:
for file in listdir(root_path):After:
for file in sorted(listdir(root_path)):Don't forget, that listdir is from os imported.
You can import functions, classes and names form modules with:
from os import listdirThen you get the name listdir on module level, which is from
os
.If you have Chinese characters in your file names, good luck.
The Unicode support is not good with Python 2.7
So if you require an Argument why not to use Python 2.7:
It is dangerous, because there are no more security patches.
If you're locked in an Env without internet access, this is ok.
If the device has internet access, Python 2.7 should not be used because of the huge security risks.
You can look, which Security Patches Python 3.x got since Python 2.7 were stopped with development.
It's a long list and very often the parsers do have some issues.
Last thing i saw, was an change of the module
urllib.parse
. Python 2.7 does not get this important updates.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!