I am using below to remove files from disk.
def match_files(dir, pattern):
for dirname, subdirs, files in os.walk(dir):
for f in files:
if f.endswith(pattern):
yield os.path.join(dirname, f)
# Remove all files in the current dir matching *.txt
for f in match_files(dn, '.txt'):
os.remove(f)
What I would to remove files from disk that "was not updated today." List the files from today. Check against to update list.
Besides os.stat you could use os.path.getmtime or os.path.getctime, the pro's / con's of which are discussed on this question. You can use datetime.datetime.fromtimestamp to convert the timestamp returned into a datetime object, and then you can do whatever you want. In this example I'll remove files not modified today, create a list of remaining files:
from datetime import datetime, timedelta
today = datetime.now().date()
remaining = []
for f in match_files(dn, '.txt'):
mtime = datetime.fromtimestamp(os.path.getmtime(f)).date()
if mtime != today:
os.remove(f)
else:
remaining.append(f)
What is "pattern" ?
Otherwise, the "os.stat" gives the date of the file. Here a sample with the "last mod" date.
stats = os.stat(file)
lastmod_date = time.localtime(stats[8])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With