Fix PermissionError in Python
Error Reference
PermissionError: [Errno 13] Permission denied
The file exists, but the OS refused the operation. Here's how to find out why.
Checklist
- Is it actually a directory?
open('data/')raises IsADirectoryError on Linux/macOS but PermissionError on Windows — point at a file, not a folder. - Do you own the file? On Linux/macOS, check with
ls -l; fix withchmod/chownrather than running as root. - Is the file open elsewhere? On Windows, a file open in Excel or another process is locked.
- Writing to a protected location? System directories (
C:\Program Files,/usr/lib) reject writes from normal users — write to a user or temp directory instead.
Diagnose
import os
path = 'report.xlsx'
print(os.access(path, os.R_OK)) # readable?
print(os.access(path, os.W_OK)) # writable?
print(os.path.isdir(path)) # accidentally a directory?
Or handle it where a fallback makes sense:
try:
with open('report.xlsx', 'w') as f:
f.write(data)
except PermissionError:
print('Close the file if it is open in another program.')
Write somewhere you own
Instead of fighting protected locations, target directories the current user controls:
from pathlib import Path
import tempfile
out = Path.home() / 'reports' # user's home directory
out.mkdir(exist_ok=True)
tmp = Path(tempfile.gettempdir()) # always writable temp dir
Windows file locks
The most common Windows cause: the file is open in Excel, a previewer, or your own code (an unclosed handle from an earlier run). Close the program — and in your own code, always use with blocks so handles release deterministically:
with open('report.csv', 'w', newline='') as f:
f.write(rows)
# handle closed here, next open() won't be locked out
Frequently Asked Questions
What does "[Errno 13] Permission denied" mean?
Errno 13 (EACCES) is the operating system telling Python the process lacks rights for that operation on that path — reading, writing, or executing. PermissionError is a subclass of OSError, so except OSError catches it too.
Should I just run my script as administrator or with sudo?
Usually no — that masks the real problem and creates files a normal user then cannot touch, making things worse. Prefer fixing ownership (chown/chmod on Unix) or writing to a directory your user owns. Reserve elevation for operations that genuinely require it, like installing system-wide software.
Why does os.remove raise PermissionError on Windows?
Windows refuses to delete a file that any process still has open — including your own unclosed file handle. Close handles with a with block before deleting. Read-only attributes also block deletion; clear them first.
import os, stat
os.chmod('locked.txt', stat.S_IWRITE) # clear read-only flag
os.remove('locked.txt')