[英]Getting WinError 5 Access is Denied
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.")
我正在運行此腳本以刪除下載文件夾中早於30天的任何文件。
我收到WindowsError: [Error 5]
告訴我訪問被拒絕。
我嘗試以admin身份運行pyCharm,以用戶和管理員身份從命令行運行。 我具有管理權限,但似乎無法解決這個問題。
您有一些錯誤。 我將從頂部開始,一直往下走。
dir = os.getcwd()
這是無效代碼,因為您從未引用dir
。 任何短毛絨都應該警告您。 刪除它。
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...
請注意, executionDate
現在總是現在的時間之前30天。
if currTime > executionDate:
什么? 我們為什么要測試呢? 我們已經知道executionDate
現在是30天之前!
os.remove(filePath)
您要刪除目錄嗎? ??
你現在要做的,我想,是檢查每個文件在目錄中,比較其創建時間戳(或最后修改的時間戳?我不知道)至三十天前值,並刪除該文件,如果可能。 您需要os.stat
和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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.