PermissionError
PermissionError: [Errno 13] Permission denied: '/etc/shadow'
Traceback
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(f.read())
PermissionError: [Errno 13] Permission denied: '/etc/shadow'What causes this error
The process does not have sufficient permissions to perform the requested filesystem operation. This happens when reading protected files, writing to read-only locations, or executing files without execute permission.
How to fix it
Check file permissions with `ls -la` or `os.access()`. Adjust permissions with `chmod`/`chown` as needed. Avoid running as root — instead, grant specific permissions. Use try/except to handle permission denials gracefully.
Code that causes this error
with open("/etc/shadow") as f:
print(f.read())Fixed code
import os
path = "/etc/shadow"
if os.access(path, os.R_OK):
with open(path) as f:
print(f.read())
else:
print(f"No read permission for {path}")About PermissionError
A PermissionError is raised when an operation is attempted without adequate access rights. This is a subclass of OSError and corresponds to the POSIX errno EACCES. It appears when trying to read, write, or execute files without the necessary permissions, when accessing system files as a regular user, or when attempting to bind to privileged network ports (below 1024) without root access.
On Unix systems, file permissions are controlled by the owner/group/other model with read/write/execute bits. On Windows, the NTFS ACL system controls access. The solution depends on the context: for files you own, use `chmod` to adjust permissions; for system files, consider whether your code actually needs that level of access or if there is a safer alternative.
Running everything as root is strongly discouraged — instead, grant the minimum necessary permissions to the specific files and directories your application needs.
Common scenarios
Running scripts without sufficient file system permissions
Connecting to servers that are not running or are unreachable
Installing Python packages without proper environment setup
Running out of disk space or file descriptors during I/O operations