Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, Deleting all files in a folder older than X days

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?

like image 609
user1681573 Avatar asked Sep 18 '12 21:09

user1681573


People also ask

How do I delete a folder older than x days?

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.


1 Answers

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).

like image 97
kindall Avatar answered Sep 23 '22 17:09

kindall