PermissionError: [Errno 13] Permission denied
PermissionError: [Errno 13] Permission denied
DodaTech
2 min read
PermissionError: [Errno 13] Permission denied means the operating system denied your Python process access to a file or directory based on the current user’s permissions.
What It Means
The user running the Python process doesn’t have the required read, write, or execute permission for the file or directory you’re trying to access. This is an OS-level restriction, not a Python issue.
Why It Happens
- Writing to a file without write permission
- Reading a file without read permission
- Executing a directory without execute permission
- Trying to open a file that’s owned by another user
- The file is locked by another process (Windows)
- Trying to create a file in a system-protected directory (e.g.
/usr,/etc) - Running as a regular user when root privileges are needed
How to Fix It
Step 1: Check file permissions
# List permissions, owner, and group
ls -la /path/to/fileThe output shows permissions like -rw-r--r-- (owner: rw-, group: r–, others: r–).
Step 2: Change file permissions with chmod
# Add read/write for the owner
chmod u+rw /path/to/file
# Add read for everyone
chmod a+r /path/to/file
# Make a file executable
chmod +x script.py
# Give full access to owner (read, write, execute)
chmod 700 /path/to/fileStep 3: Change file ownership
# Change owner to your user
sudo chown $(whoami) /path/to/file
# Change owner and group
sudo chown $(whoami):$(id -gn) /path/to/fileStep 4: Use a different directory for writing
Write files where your user has permission:
# BAD — system directory
with open("/etc/myapp/config.json", "w") as f:
f.write(data)
# GOOD — user's home directory
from pathlib import Path
home = Path.home()
with open(home / "config.json", "w") as f:
f.write(data)
# Or use /tmp
import tempfile
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write(data)
print(f.name)Step 5: Run with elevated privileges (when necessary)
# Only when you genuinely need root access
sudo python script.pyStep 6: Fix in Python with os.chmod
import os
import stat
path = "script.sh"
# Add execute permission for the owner
os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR)Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro