简体   繁体   English

获取WinError 5访问被拒绝

[英]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.")

I am running this script to delete any file in my download folder which is older then 30 days. 我正在运行此脚本以删除下载文件夹中早于30天的任何文件。

I get WindowsError: [Error 5] telling me that access is denied. 我收到WindowsError: [Error 5]告诉我访问被拒绝。

I have tried running pyCharm as admin, running from command line as user and administrator. 我尝试以admin身份运行pyCharm,以用户和管理员身份从命令行运行。 I have administrative rights but I cannot seem to get past this issue. 我具有管理权限,但似乎无法解决这个问题。

You have a few errors. 您有一些错误。 I'll start at the top and work my way down. 我将从顶部开始,一直往下走。

dir = os.getcwd()

This is dead code, since you never reference dir . 这是无效代码,因为您从未引用dir Any linter should warn you about this. 任何短毛绒都应该警告您。 Delete it. 删除它。

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

Note that executionDate is now always 30 days before the time right now. 请注意, executionDate现在总是现在的时间之前30天。

if currTime > executionDate:

What? 什么? Why are we testing this? 我们为什么要测试呢? We already know executionDate is 30 days before right now! 我们已经知道executionDate现在是30天之前!

    os.remove(filePath)

You're trying to remove the directory? 您要删除目录吗? Huh? ??


What you're trying to do, I think, is to check each file in the directory, compare its creation timestamp (or last modified timestamp? I'm not sure) to the thirty-days-ago value, and delete that file if possible. 你现在要做的,我想,是检查每个文件在目录中,比较其创建时间戳(或最后修改的时间戳?我不知道)至三十天前值,并删除该文件,如果可能。 You want os.stat and os.listdir 您需要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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM