作者:朱金灿
来源:clever101的专栏

为什么大多数人学不会人工智能编程?>>>

[WinError 5]拒绝访问的错误的分析

  [WinError 5]拒绝访问的错误出现主要是因为用户程序缺乏访问访问这个文件夹或文件的权限。

如何处理这样的错误

  网上很多不靠谱的文章说是修改python.exe的权限,实际上不太管用(反正在我的机器上没用)。如果你是想删掉这个文件或文件夹,可以让Python运行cmd命令强制删除此文件,具体代码如下:

import os
os.system('del "PackageCache\com.unity.textmeshpro@1.3.0\Tests\Editor.meta" /F')

  具体参考这篇文章:解决Python 删除只读文件/文件夹报错:[WinError 5] 拒绝访问。
  如果你是想跳过访问该文件或文件夹,建议使用try except 跳过无权限访问的文件夹。具体代码如下:

# 获取文件或文件夹大小
# 如果该函数没有try except,在访问'C:\\ProgramData\\Application Data'时会出现# [WinError 5]拒绝访问的错误 
def getFileFolderSize(fileOrFolderPath):
    totalSize = 0

    if not os.path.exists(fileOrFolderPath):
        return totalSize

    if os.path.isfile(fileOrFolderPath):
        totalSize = os.path.getsize(fileOrFolderPath)  # 5041481
        return totalSize

    try:
        for ff in os.listdir(fileOrFolderPath):
            wholepath = os.path.join(fileOrFolderPath, ff)
            if os.path.isdir(wholepath):
                curSubFolderSize = getFileFolderSize(wholepath)
                totalSize +=curSubFolderSize

            if os.path.isfile(wholepath):
                curSubFileSize = os.path.getsize(wholepath)
                totalSize += curSubFileSize
    except:  # 如果风险语句未能过关会跳来这里继续
        os.chdir(os.pardir)

    return totalSize
``

更多推荐

python程序中如何合理处理[WinError 5]拒绝访问的错误