Skip to content
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/file

The 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/file

Step 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/file

Step 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.py

Step 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)
What does 'ls -la' show and how do I read permissions?
ls -la shows: file type + permissions (e.g. -rwxr-xr--), number of links, owner, group, size, date, filename. The permissions break down as: type (- file, d directory), then three groups of rwx (read, write, execute) for owner, group, and others.
Should I always use sudo to fix PermissionError?
No. Using sudo unnecessarily is a security risk. First try changing the file’s permissions or ownership to your user, or write to a directory you own (like your home directory). Only use sudo when you genuinely need system-level access.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro