How to Fix PermissionError: [Errno 13] in Python
In this tutorial, you'll learn about How to Fix PermissionError: [Errno 13] in Python. We cover key concepts, practical examples, and best practices.
Python raises PermissionError: [Errno 13] Permission denied when the user running the script does not have the required filesystem permissions.
The Wrong Way
with open("/etc/some_config.conf", "w") as f:
f.write("config data")
This produces:
Traceback (most recent call last):
File "script.py", line 1, in <module>
with open("/etc/some_config.conf", "w") as f:
PermissionError: [Errno 13] Permission denied: '/etc/some_config.conf'
The Right Way
Check permissions before writing, and use a location the user can write to:
import os
from pathlib import Path
target = Path.home() / "some_config.conf"
if os.access(target.parent, os.W_OK):
target.write_text("config data")
print(f"Written to {target}")
else:
print(f"Cannot write to {target.parent}")
Output:
Written to /home/user/some_config.conf
Step-by-Step Fix
1. Use a user-writable directory
from pathlib import Path
# User's home directory
config_path = Path.home() / "config.conf"
# Or a temp directory
import tempfile
temp_path = Path(tempfile.gettempdir()) / "config.conf"
2. Run with elevated privileges when necessary
sudo python3 script.py
Only use this when the script genuinely needs system-level access.
3. Check and fix file permissions
import os
import stat
filepath = "script.sh"
# Make file executable
os.chmod(filepath, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
4. Use try-except for graceful handling
try:
with open("/etc/config.conf", "w") as f:
f.write("data")
except PermissionError:
print("Permission denied. Run with sudo or use a different path.")
Prevention Tips
- Write to user-writable directories like home or temp.
- Use
os.access()to check permissions before operations. - Never run scripts as root unless absolutely necessary.
- Use
pathlib.Path.home()for user-specific files. - Check that parent directories are writable, not just the target file.
Common Mistakes with permissionerror
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro