获取WinError 5访问被拒绝

时间:2018-07-13 23:11: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]告诉我访问被拒绝。

我尝试以admin身份运行pyCharm,以用户和管理员身份从命令行运行。我拥有管理权,但似乎无法克服这个问题。

1 个答案:

答案 0 :(得分:2)

您有一些错误。我将从顶部开始,一直往下走。

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)

您要删除目录吗?嗯?


我认为

您正在尝试 要做的是检查目录中的每个文件,比较其创建时间戳(或上次修改的时间戳? (不确定),直到30天前的值,然后删除该文件(如果可能)。您需要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))