PermissionError: [Errno 13] Permission denied: '/path/to/file'
Your Python script doesn’t have permission to read, write, or execute the file.
Fix 1: Check file permissions
ls -la /path/to/file
If you need write access:
chmod 644 /path/to/file # Read/write for owner, read for others
chmod 755 /path/to/folder # For directories
Fix 2: You’re trying to write to a read-only location
# ❌ Can't write to system directories without sudo
with open("/etc/myconfig.txt", "w") as f:
f.write("data")
# ✅ Write to your home directory or project folder
with open("./myconfig.txt", "w") as f:
f.write("data")
Fix 3: File is open by another process
On Windows, a file can be locked by another program:
# ✅ Make sure to close files properly
with open("data.txt", "w") as f:
f.write("data")
# File is automatically closed after the with block
Fix 4: Directory doesn’t exist
import os
# ✅ Create directory if it doesn't exist
os.makedirs("output/data", exist_ok=True)
with open("output/data/result.txt", "w") as f:
f.write("data")