获取WinError 5访问被拒绝

2024-10-08 19:19:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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,以用户和管理员的身份从命令行运行。我有管理权,但我似乎无法摆脱这个问题。你知道吗


Tags: importiftimeos管理员downloadsdir身份
1条回答
网友
1楼 · 发布于 2024-10-08 19:19:58

你有一些错误。我从最上面开始,一路往下。你知道吗

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

相关问题 更多 >

    热门问题