python - 获取 WinError 5 访问被拒绝
问题描述
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]
告诉我访问被拒绝。
我尝试以管理员身份运行 pyCharm,以用户和管理员身份从命令行运行。我有管理权限,但我似乎无法解决这个问题。
解决方案
你有几个错误。我将从顶部开始,然后一路向下。
dir = os.getcwd()
这是死代码,因为您从不引用dir
. 任何 linter 都应该对此发出警告。删除它。
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)
您正在尝试删除目录?嗯?
我认为,您要做的是检查目录中的每个文件,将其创建时间戳(或上次修改的时间戳?我不确定)与 30 天前的值进行比较,如果可能的。你想要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))
推荐阅读
- google-apps-script - 如何修复以前依赖于 Fusion Tables Advanced Service v1 的谷歌应用程序脚本?
- php - 如何在php中编辑文件?
- kubernetes - Get .pem files in kubernetes with secret certificate
- selenium - 硒随机失效
- python - Changing grid position with a button in python
- amazon-web-services - AWS S3 File Copy - monitor when a file doesn't get moved into S3 Bucket
- url - mc_eid showing [UNIQID] in MailChimp link after enabling tracking
- java - 如何在 adnroid 中获取 recyclerView 项目的 X 和 Y 坐标?
- android-fragments - 带有 RecyclerView 滚动问题的垂直 ViewPager2
- android - Android : Branch SDK Api Error after changed date on device