I’m trying to create a script that checks a folder for files older than 7 days and deletes them, but only if a file younger than 1 day from “now” exists.
So, if a new file has been created that is less than 1 day old, then delete all files older than seven days.
This is my script –
import os, time
path = r"C:\Temp" #working path#
now = time.time()
for f in os.listdir(path):
f = os.path.join(path, f)
if os.stat(os.path.join(path, f).st_mtime < now -1 * 86400 and\ #checking new file#
if os.stat(os.path.join(path,f)).st_mtime < now - 7 * 86400: #checking old files#
if os.path.isfile(f):
os.remove(os.path.join(path, f)
I’m getting syntax errors in my line checking for old files. Am I not indenting correctly, is this an invalid way to code this? A program creates a new file each day. This script checks to see if that file has been created, and if this is true, then checks for files older than seven days and deletes them. I don’t understand the syntax error, the logic is correct, am I right?
1 Answer