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:\users\%myusername%\downloads"
now = time.time()
for f in os.listdir(path):
if os.stat(f).st_mtime < now - 7 * 86400:
if os.path.isfile(f):
os.remove(os.path.join(path, f))
When I run the script, I get:
Error2 - system cannot find the file specified,
and it gives the filename. What am I doing wrong?
os.listdir()returns a list of bare filenames. These do not have a full path, so you need to combine it with the path of the containing directory. You are doing this when you go to delete the file, but not when youstatthe file (or when you doisfile()either).Easiest solution is just to do it once at the top of your loop:
Now
fis the full path to the file and you just usefeverywhere (change yourremove()call to just useftoo).