error python

Python PermissionError

Understanding Python PermissionError - raised when trying to perform an operation without adequate access permissions.

What It Means

PermissionError (a subclass of OSError) is raised when an operation is attempted without sufficient filesystem or operating system permissions. The error message reads: [Errno 13] Permission denied: 'filename'. This occurs when trying to read, write, execute, or delete files or directories you don’t have access to.

Common Causes

  • Trying to write to a read-only file or directory
  • Accessing files owned by root or another user
  • Writing to system directories without elevated privileges
  • File is locked by another process
  • SELinux or AppArmor policies blocking access
  • Docker container running as non-root without proper file ownership
  • Trying to bind to a privileged port (< 1024) without root access

How to Fix

Check and fix file permissions

# Check current permissions
ls -la /path/to/file

# Fix permissions
chmod 644 /path/to/file      # Read/write for owner, read for others
chmod 755 /path/to/directory  # Includes execute for directories

# Change ownership
sudo chown $USER:$USER /path/to/file

Handle permission errors in code

import os

try:
    with open("/etc/protected_file", "w") as f:
        f.write("data")
except PermissionError:
    # Fall back to a writable location
    fallback_path = os.path.expanduser("~/protected_file")
    with open(fallback_path, "w") as f:
        f.write("data")
    print(f"Written to fallback path: {fallback_path}")

Write to user-accessible directories

import os
from pathlib import Path

# Bad: writing to system directories
with open("/var/log/myapp.log", "w") as f:  # PermissionError
    f.write("log entry")

# Good: write to user-writable paths
log_dir = Path.home() / ".myapp" / "logs"
log_dir.mkdir(parents=True, exist_ok=True)
with open(log_dir / "myapp.log", "a") as f:
    f.write("log entry\n")

# Good: use temp directory
import tempfile
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
    f.write("temporary data")
    print(f"Written to: {f.name}")

Check permissions before operating

import os

path = "/path/to/file"

# Check read permission
if os.access(path, os.R_OK):
    with open(path) as f:
        data = f.read()
else:
    print(f"No read permission for {path}")

# Check write permission
if os.access(path, os.W_OK):
    with open(path, "w") as f:
        f.write("data")

# Check directory write permission
dir_path = os.path.dirname(path)
if os.access(dir_path, os.W_OK):
    print("Can write to directory")

Fix in Docker

# Create a non-root user with proper permissions
FROM python:3.12-slim
RUN useradd -m appuser

WORKDIR /app
COPY --chown=appuser:appuser . .

# Create writable directories
RUN mkdir -p /app/data && chown appuser:appuser /app/data

USER appuser
CMD ["python", "app.py"]

Fix port binding issues

# Error: PermissionError: [Errno 13] Permission denied
# when trying to bind to port 80

# Fix: use a non-privileged port (>= 1024)
app.run(host="0.0.0.0", port=8080)

# Or use authbind/setcap to allow binding low ports
# sudo setcap 'cap_net_bind_service=+ep' $(which python3)