PermissionError: [Errno 13] Permission denied
Error message
[Errno 13] Permission denied: 'protected.txt'
Quick summary
You tried to read, write, or execute a file or resource without the necessary permissions.
Why this happens
Writing to a read-only file
Reading a file without read permission
Creating a file in a directory without write permission
Executing a file without execute permission
Minimal example
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")Writing to a system file requires elevated permissions. Handle with try/except PermissionError.
How to diagnose
Check file permissions with os.stat() or ls -l
Verify you have the required access level
Check if the file is locked by another process
How to fix
Change file permissions with chmod (Unix) or Properties (Windows)
Run the script with elevated permissions if appropriate
Use try/except PermissionError to handle the error gracefully
How to prevent
Check permissions before file operations
Use appropriate user accounts with correct permissions
Related Resources
Related Lessons
- File Handling
File permissions.