I\'m trying to write a python script to delete all files in a folder older than X days. This is what I have so far:
import os, time, sys
path = r\"c:\\user
i did it in more sufficient way
import os, time
path = "/home/mansoor/Documents/clients/AirFinder/vendors"
now = time.time()
for filename in os.listdir(path):
filestamp = os.stat(os.path.join(path, filename)).st_mtime
filecompare = now - 7 * 86400
if filestamp < filecompare:
print(filename)
There's script which delete files only if you running out of space, this is good fit for logs and backups in production environment.
Delete old files will eventually remove all your backups if new backups are not being added
https://gist.github.com/PavelNiedoba/811a193e8a71286f72460510e1d2d9e9
With comprehensions, Can be:
import os
from time import time
p='.'
result=[os.remove(file) for file in (os.path.join(path, file) for path, _, files in os.walk(p) for file in files) if os.stat(file).st_mtime < time() - 7 * 86400]
print(result)
May be see: https://ideone.com/Bryj1l
I think the new pathlib thingy together with the arrow module for dates make for neater code.
from pathlib import Path
import arrow
filesPath = r"C:\scratch\removeThem"
criticalTime = arrow.now().shift(hours=+5).shift(days=-7)
for item in Path(filesPath).glob('*'):
if item.is_file():
print (str(item.absolute()))
itemTime = arrow.get(item.stat().st_mtime)
if itemTime < criticalTime:
#remove it
pass
Here's the output showing the full paths offered by pathlib. (No need to join.)
C:\scratch\removeThem\four.txt
C:\scratch\removeThem\one.txt
C:\scratch\removeThem\three.txt
C:\scratch\removeThem\two.txt
You need to give it the path also or it will look in cwd.. which ironically enough you did on the os.remove
but no where else...
for f in os.listdir(path):
if os.stat(os.path.join(path,f)).st_mtime < now - 7 * 86400:
You need to use if os.stat(os.path.join(path, f)).st_mtime < now - 7 * 86400:
instead of if os.stat(f).st_mtime < now - 7 * 86400:
I find using os.path.getmtime
more convenient :-
import os, time
path = r"c:\users\%myusername%\downloads"
now = time.time()
for filename in os.listdir(path):
# if os.stat(os.path.join(path, filename)).st_mtime < now - 7 * 86400:
if os.path.getmtime(os.path.join(path, filename)) < now - 7 * 86400:
if os.path.isfile(os.path.join(path, filename)):
print(filename)
os.remove(os.path.join(path, filename))