Skip to content

PermissionError: [Errno 13] Permission 拒绝

错误信息

                [Errno 13] Permission 拒绝: '受保护.txt'
              

快速摘要

你 tried 到读取, 编写, or 执行 file or resource 不使用必要 permissions.

为什么发生

  • 编写到 读取-仅 file

  • 读取 file 不使用读取 permission

  • 创建 file in directory 不使用编写 permission

  • 执行 file 不使用执行 permission

最小示例

✗ 错误代码
with open("/etc/passwd", "w") as f:  # PermissionError
    f.write("test")
✓ 修复代码
try:
    with open("/etc/passwd", "w") as f:
        f.write("test")
except PermissionError:
    print("Permission denied — cannot write to this file")

编写到 系统 file 需要 elevated permissions. Handle 使用 try/except PermissionError.

如何诊断

  • 检查 file permissions 使用 os.stat() or ls -l

  • 验证你 有必需 access level

  • 检查如果 file 是 locked 通过 another 处理

如何修复

  • 更改 file permissions 使用 chmod (Unix) or 属性 (Windows)

  • 运行 script 使用 elevated permissions 如果 appropriate

  • Use try/except PermissionError 到 handle 错误 gracefully

如何预防

  • 检查 permissions 之前 file 操作

  • Use appropriate 用户 accounts 使用正确 permissions

相关资源

相关术语

相关课程

← 返回语言