What this error means
You tried to read, write, or delete a file or directory, but your Python program doesn't have the necessary permissions. This is a system-level restriction, not a Python bug.
Common causes
- The file is open in another program (like a text editor).
- You don't have read/write permissions for that file or directory.
- You're trying to write to a system-protected location (like C:\Windows).
- The file is read-only.
Example that causes the error
# File is open in another program:
with open('data.txt', 'w') as f: # PermissionError if file is open elsewhere
f.write("Hello")
# Or trying to write to protected location:
with open('C:/Windows/system.txt', 'w') as f: # PermissionError
f.write("test")
How to fix it: close other programs
Close any programs that have the file open:
# Make sure the file is closed in:
# - Text editors
# - Excel/Word if it's an Office file
# - Other Python scripts
# - File managers with the file selected
# Then try again:
with open('data.txt', 'w') as f:
f.write("Hello") # OK if file is closed
Check file permissions
import os
file_path = 'data.txt'
if os.access(file_path, os.W_OK):
with open(file_path, 'w') as f:
f.write("Hello")
else:
print("No write permission for this file")
Use try-except
try:
with open('data.txt', 'w') as f:
f.write("Hello")
except PermissionError:
print("Permission denied. Close the file in other programs first.")
Run with appropriate permissions
On Windows, you might need to run your Python script as Administrator. On Linux/Mac, you might need to use chmod to change file permissions.