首页 > 解决方案 > 获取 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,以用户和管理员身份从命令行运行。我有管理权限,但我似乎无法解决这个问题。

标签: python

解决方案


你有几个错误。我将从顶部开始,然后一路向下。

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

推荐阅读