import os
import time
filePath = 'C:\\Users\\Ben\\Downloads'
dir =os.getcwd()
currTime = time.time()
day = (30 * 86400)
executionDate = currTime - day
if(currTime > executionDate):
os.remove(filePath)
else:
print("Nothing older than 30 days in download file.")
I am running this script to delete any file in my download folder which is older then 30 days.
I get WindowsError: [Error 5]
telling me that access is denied.
I have tried running pyCharm as admin, running from command line as user and administrator. I have administrative rights but I cannot seem to get past this issue.
You have a few errors. I'll start at the top and work my way down.
dir = os.getcwd()
This is dead code, since you never reference dir
. Any linter should warn you about this. Delete it.
currTime = time.time() # nit: camelCase is not idiomatic in Python, use curr_time or currtime
day = (30 * 86400) # nit: this should be named thirty_days, not day. Also 86400 seems like a magic number
# maybe day = 60 * 60 * 24; thirty_days = 30 * day
executionDate = currTime - day # nit: camelCase again...
Note that executionDate
is now always 30 days before the time right now.
if currTime > executionDate:
What? Why are we testing this? We already know executionDate
is 30 days before right now!
os.remove(filePath)
You're trying to remove the directory? Huh?
What you're trying to do, I think, is to check each file in the directory, compare its creation timestamp (or last modified timestamp? I'm not sure) to the thirty-days-ago value, and delete that file if possible. You want os.stat
and os.listdir
for fname in os.listdir(filePath):
ctime = os.stat(os.path.join(filePath, fname)).st_ctime
if ctime < cutoff: # I've renamed executionDate here because it's a silly name
try:
os.remove(os.path.join(filePath, fname))
except Exception as e:
# something went wrong, let's print what it was
print("!! Error: " + str(e))
else:
# nothing went wrong
print("Deleted " + os.path.join(filePath, fname))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.