You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python遍历文件夹计算大小遇权限拒绝问题求解

问题:遍历文件夹统计空间时遇到权限拒绝错误

我写了一个Python脚本用来遍历文件夹并统计占用空间,找出占用最大的文件夹,但访问受管理员保护的文件夹时触发了权限错误,报错PermissionError: [WinError 5] 拒绝访问。

我的代码:

import os
import plotly.express as px

values = []
names = []
total = 0
ratio = []

def get_dir_size(pathall):
    dirlist = []
    with os.scandir(pathall) as maindir:
        for path in maindir:
            if path.is_dir():
                total = 0
                with os.scandir(path) as it:
                    for entry in it:
                        if entry.is_file():
                            total += entry.stat().st_size
                        elif entry.is_dir():
                            total += get_indir_size(entry.path)
                dirlist.append([path.name, total])
    return dirlist

def get_indir_size(path):
    total = 0
    with os.scandir(path) as it:
        for entry in it:
            if entry.is_file():
                total += entry.stat().st_size
            elif entry.is_dir():
                total += get_indir_size(entry.path)
    return total


folder = input('folder: \n>')
result = get_dir_size(folder)

for inst in result:
    values.append(inst[1])
    names.append(inst[0])

for value in values:
    total += value

for value in values:
    ratio.append(int(value/total*1000)/10)

print(result)
print(names, ratio)
pie = px.pie(values=ratio, names=names, width=1000, height=1000)
pie.show()

报错详情:

Traceback (most recent call last):
  File "E:\Programmation\folder analizer\__main__.py", line 36, in <module>
    result = get_dir_size(folder)
  File "E:\Programmation\folder analizer\__main__.py", line 20, in get_dir_size
    total += get_indir_size(entry.path)
  File "E:\Programmation\folder analizer\__main__.py", line 26, in get_indir_size
    with os.scandir(path) as it:
PermissionError: [WinError 5] 拒绝访问: 'C:\\Users\\AppData\\Local\\Application Data'

解决方案

1. 给文件操作添加异常捕获

在涉及文件夹扫描和文件状态获取的代码块中加入try-except,遇到权限错误时跳过当前路径,避免程序直接崩溃。修改后的代码如下:

import os
import plotly.express as px

values = []
names = []
total = 0
ratio = []

def get_dir_size(pathall):
    dirlist = []
    try:
        with os.scandir(pathall) as maindir:
            for path in maindir:
                if path.is_dir():
                    total = 0
                    try:
                        with os.scandir(path) as it:
                            for entry in it:
                                try:
                                    if entry.is_file():
                                        total += entry.stat().st_size
                                    elif entry.is_dir():
                                        total += get_indir_size(entry.path)
                                except PermissionError:
                                    print(f"无权限访问: {entry.path}")
                        dirlist.append([path.name, total])
                    except PermissionError:
                        print(f"无权限访问文件夹: {path.path}")
    except PermissionError:
        print(f"无权限访问根文件夹: {pathall}")
    return dirlist

def get_indir_size(path):
    total = 0
    try:
        with os.scandir(path) as it:
            for entry in it:
                try:
                    if entry.is_file():
                        total += entry.stat().st_size
                    elif entry.is_dir():
                        total += get_indir_size(entry.path)
                except PermissionError:
                    print(f"无权限访问: {entry.path}")
    except PermissionError:
        print(f"无权限访问文件夹: {path}")
    return total


folder = input('folder: \n>')
result = get_dir_size(folder)

for inst in result:
    values.append(inst[1])
    names.append(inst[0])

total = sum(values) if values else 0
ratio = [int(value/total*1000)/10 if total !=0 else 0 for value in values]

print(result)
print(names, ratio)
pie = px.pie(values=ratio, names=names, width=1000, height=1000)
pie.show()

2. 以管理员身份运行脚本

如果确实需要访问受保护的系统文件夹,右键点击Python解释器或脚本文件,选择以管理员身份运行,获取足够权限访问这类路径。

3. 主动跳过特殊系统文件夹

像Application Data这类是系统链接文件夹(junction点),本身不占用实际空间,还容易触发权限问题。可以在遍历逻辑中加入判断跳过:

# 在遍历文件夹的循环中添加
if path.is_symlink() or path.name in ['Application Data', 'Local Settings']:
    continue

内容的提问来源于stack exchange,提问作者Trom al

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 22:27:30