Encountering the IOError: [Errno 13] Permission denied message can be confusing, especially for beginners. This error typically means your Python script tried to access a file or directory without having the right permissions.
It’s a common and fixable problem — so don’t worry. This guide will walk you through the causes and simple solutions to resolve it.
What Causes This Error?
1. Writing to a File or Directory Without Permission
Trying to write to a file that’s read-only or located in a system-protected folder can trigger this error.
2. File Already Opened or Locked
If another process or program is using the file, Python may not be allowed to access it.
3. Accessing Restricted System Paths
Attempting to read or write files in locations like /etc/
, C:\Windows\System32
, or other admin-only directories can raise this error.
4. Running Without Administrative Privileges
Your script might need elevated permissions that it doesn’t currently have.
How to Fix It
Check File Permissions
Make sure the file or directory is writable.
with open("example.txt", "w") as file:
file.write("Hello, world!")
Why it works: This ensures the script opens a file in a directory where the user has write access.
Run Script with Administrative Privileges
If you’re using the terminal or command prompt, try running the script as an admin.
Why it works: This gives the script temporary elevated permissions to access protected files or folders.
Use a Different Directory
Avoid writing to system folders. Choose a user-friendly path like your home directory or Documents
.
with open("C:/Users/YourName/Documents/example.txt", "w") as file:
file.write("Safe location")
Why it works: You’re writing to a directory where standard users usually have permission.
Check for File Locks
Ensure no other application (like Word or Excel) is locking the file.
Why it works: Python cannot write to a file currently in use by another application.
Real Example
The Error Version
with open("/etc/config.txt", "w") as file:
file.write("Trying to write")
Error: IOError: [Errno 13] Permission denied: '/etc/config.txt'
The Fixed Version
with open("my_config.txt", "w") as file:
file.write("Saved locally instead")
Explanation: This version writes to a local file the user has access to.
Tips to Prevent This Error
- Avoid writing to system folders unless absolutely necessary.
- Use
try/except
blocks to catch and handle permission errors gracefully. - Always close files properly or use the
with
statement to handle them automatically.
Conclusion
“Permission denied” errors are common, especially when dealing with file operations in Python. With a few adjustments — like choosing safe file paths or running your script with proper permissions
Bookmark this guide for future reference, and keep experimenting with confidence!