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?
Delete files older than X days using ForFiles on Windows 10Search for Command Prompt, right-click the result and select the Run as administrator option. In the command, change "C:\path\to\folder" specifying the path to the folder you want to delete files and change /d -30 to select files with a last modified date.
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 you stat
the file (or when you do isfile()
either).
Easiest solution is just to do it once at the top of your loop:
f = os.path.join(path, f)
Now f
is the full path to the file and you just use f
everywhere (change your remove()
call to just use f
too).
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