PermissionError: operation not permitted
Quick summary
You tried to read, write, or execute a file your process does not have permission for — Python raises PermissionError.
Why this happens
The file or directory has read-only or restricted permissions that prevent the operation you attempted
The script is running as a non-root user and the file is owned by root or another user with no group/world access
On Windows, the file is locked by another process or marked as read-only through file attributes
Minimal example
with open('/etc/protected_config', 'w') as f: # PermissionError
f.write('new config')try:
with open('/etc/protected_config', 'w') as f:
f.write('new config')
except PermissionError:
print('Cannot write: insufficient permissions. Try running as admin.')Wrapping the file operation in a try/except for PermissionError lets you provide a helpful message instead of crashing.
How to diagnose
Check file permissions with os.stat() or ls -l on Unix to see the owner and permission bits
Verify which user the script is running as with os.getuid() (Unix) or getpass.getuser()
On Windows, check if the file is open in another application or has the read-only attribute set
How to fix
Change file permissions with chmod or os.chmod() to grant the needed access level to your user
Run the script as a user with appropriate permissions, or use sudo for system files (with caution)
Close the file in the other application or remove the read-only attribute before retrying the operation
How to prevent
Set appropriate file permissions when creating files so later operations do not fail with permission errors
Handle PermissionError with a try/except and provide a user-friendly message explaining the access issue