How to Resolve Error "PermissionError: [Errno 13] Permission denied" (File Access)
The PermissionError: [Errno 13] Permission denied
is a common Python runtime error encountered when your script attempts to access a file or directory without the necessary operating system permissions, or when it tries to perform an operation that's not allowed on the target (like opening a directory as if it were a file).
This guide explains the frequent causes of this error and provides step-by-step solutions to diagnose and fix it.
Understanding PermissionError: [Errno 13]
This error, a subclass of OSError
, signals that the operating system has denied your Python script's request to access a file system resource in a particular way. The [Errno 13]
is the system error code for "Permission denied." The error message usually includes the path that caused the issue.
Common Cause 1: Trying to Open a Directory as a File
One of the most frequent reasons is providing a path that points to a directory to a function like open()
which expects a path to a file.
The Problem: Incorrect Path
import os
# ⛔️ Problem: 'my_project_folder' is a directory, not a file.
# On Windows, this might be: r'C:\Users\YourUser\Documents\my_project_folder'
directory_path = 'my_project_folder'
# --- For demonstration, create the directory if it doesn't exist ---
if not os.path.exists(directory_path):
os.makedirs(directory_path)
print(f"Created directory '{directory_path}' for demo.")
# --- End demo setup ---
try:
# Attempting to open the directory for writing
# ⛔️ PermissionError: [Errno 13] Permission denied: 'my_project_folder'
# (On some OSes, this might be IsADirectoryError instead, but PermissionError is common)
with open(directory_path, 'w', encoding='utf-8') as f:
f.write("some text\n")
except PermissionError as e:
print(f"Caught PermissionError: {e}")
except IsADirectoryError as e: # Another possibility
print(f"Caught IsADirectoryError: {e}")
Solution: Specify Full File Path (Including Filename and Extension)
Ensure your path string points to an actual file, including its name and extension (e.g., .txt
, .csv
, .json
).
import os
directory_path = 'my_project_folder' # Path to the directory
file_name = 'example.txt' # Name of the file
# ✅ Correct: Construct the full path to the FILE inside the directory
full_file_path = os.path.join(directory_path, file_name)
# On Windows, this might be: r'C:\Users\YourUser\Documents\my_project_folder\example.txt'
print(f"Attempting to open file: {full_file_path}")
try:
# Create the directory if it doesn't exist (important for os.path.join to work as expected for open)
if not os.path.exists(directory_path):
os.makedirs(directory_path)
with open(full_file_path, 'w', encoding='utf-8') as f:
f.write("Hello from Python!\n")
print(f"Successfully wrote to {full_file_path}")
# Verify content
with open(full_file_path, 'r', encoding='utf-8') as f:
print(f"Content: {f.read().strip()}")
except PermissionError as e:
print(f"Caught PermissionError: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
- Finding the Full Path: On most operating systems, you can find a file's path by right-clicking it, selecting "Properties" (Windows) or "Get Info" (macOS). Ensure you append the actual filename and its extension to the directory path you find.
- Make sure file extensions are visible in your OS file explorer to avoid mistakes.
Verifying Path Type (os.path.isfile
, os.path.isdir
)
Before attempting to open a path, you can check if it's a file or a directory using the os.path
module.
import os
path_to_check = 'my_project_folder' # This is a directory
# path_to_check = 'my_project_folder/example.txt' # This would be a file
print(f"Path: {path_to_check}")
print(f"Is it a file? {os.path.isfile(path_to_check)}") # False for directory
print(f"Is it a directory? {os.path.isdir(path_to_check)}") # True for directory
if os.path.isfile(path_to_check):
print("Path points to a file. Safe to open.")
# with open(path_to_check, 'r') as f: ...
elif os.path.isdir(path_to_check):
print("Path points to a directory. Cannot open as a regular file.")
else:
print("Path does not exist or is not a regular file/directory.")
Common Cause 2: Insufficient File/Directory Permissions
Your script might not have the necessary read, write, or execute permissions for the target file or directory.
The Problem: Access Rights
Operating systems use a permission system to control who can access files and what they can do (read, write, execute). If your Python script runs under a user account that lacks the required permission for the operation you're attempting (e.g., writing to a file in a system-protected directory), you'll get PermissionError
.
Solution: Check/Modify Permissions or Run as Administrator/Root
- Check/Modify File/Directory Permissions:
- Linux/macOS: Use
ls -l <path>
to view permissions. Usechmod
to change them (e.g.,chmod u+w filename
to give the user write permission). You might needsudo
to change permissions on files you don't own. - Windows: Right-click the file/folder -> Properties -> Security tab. Edit permissions for your user account.
- Linux/macOS: Use
- Run Script with Elevated Privileges (Use with Caution):
- Linux/macOS: Prefix your command with
sudo
:sudo python3 your_script.py
. - Windows:
- Search for "cmd" (Command Prompt) or "PowerShell".
- Right-click on it and select "Run as administrator".
- Navigate to your script's directory (
cd path\to\your\script
) and run it (python your_script.py
).
- If using an IDE like PyCharm, close it and restart it by right-clicking its icon and selecting "Run as administrator". Warning: Running scripts with elevated privileges should be done cautiously, as it grants the script broad access to your system. Only do this if you trust the script and understand the implications. It's often better to fix the underlying permissions if possible.
- Linux/macOS: Prefix your command with
Common Cause 3: File is Locked by Another Application
If the file you're trying to access (especially for writing or deleting) is currently open and locked by another program (e.g., Microsoft Excel, a text editor, another Python script), the OS may deny access.
The Problem: File In Use
The operating system often prevents simultaneous modification of a file by multiple applications to avoid data corruption.
Solution: Close the File in Other Applications
Ensure the file is not open in any other application before your Python script tries to access it. Close Excel, Word, text editors, etc., that might have the file open.
Handling File Paths Correctly
Absolute vs. Relative Paths
- Absolute Path: A full path starting from the root directory (e.g.,
C:\Users\Me\file.txt
or/home/me/file.txt
). They are unambiguous. - Relative Path: A path relative to the current working directory of your script (e.g.,
data/file.txt
). If your script is in/home/me/project/
and you useopen('output.txt', 'w')
, it tries to create/home/me/project/output.txt
. If you're having trouble with relative paths, try using an absolute path to confirm the file location, or printos.getcwd()
to see your script's current working directory.
Windows Path Formatting (Raw Strings)
On Windows, paths use backslashes (\
), which are also escape characters in Python strings (e.g., \n
is a newline). To avoid issues:
- Use Raw Strings: Prefix the path string with
r
.file_path_windows = r'C:\Users\YourName\Documents\example.txt'
- Use Forward Slashes: Python on Windows often handles forward slashes correctly in paths.
file_path_windows_forward = 'C:/Users/YourName/Documents/example.txt'
- Escape Backslashes: Use double backslashes (
\\
).file_path_windows_escaped = 'C:\\Users\\YourName\\Documents\\example.txt'
Opening All Files in a Directory (Correct Approach)
If you intend to process multiple files within a directory, you need to list the directory contents and then construct the full path for each file.
import os
directory_to_scan = 'my_data_folder' # e.g., r'C:\path\to\my_data_folder'
# Create directory and some dummy files for demo
if not os.path.exists(directory_to_scan): os.makedirs(directory_to_scan)
with open(os.path.join(directory_to_scan, "file1.txt"), "w") as f: f.write("content1")
with open(os.path.join(directory_to_scan, "file2.log"), "w") as f: f.write("content2")
try:
for entry_name in os.listdir(directory_to_scan):
full_entry_path = os.path.join(directory_to_scan, entry_name) # Construct full path
if os.path.isfile(full_entry_path): # Process only if it's a file
print(f"Processing file: {full_entry_path}")
try:
with open(full_entry_path, 'r', encoding='utf-8') as f_in:
content = f_in.read(50) # Read first 50 chars
print(f" Content (first 50 chars): '{content.strip()[:50]}...'")
except PermissionError as e_file:
print(f" Permission denied for file '{full_entry_path}': {e_file}")
except Exception as e_file_other:
print(f" Error reading file '{full_entry_path}': {e_file_other}")
except FileNotFoundError:
print(f"Error: Directory '{directory_to_scan}' not found.")
except PermissionError as e_dir:
print(f"Permission denied for directory '{directory_to_scan}': {e_dir}")
os.listdir(directory)
: Returns a list of names of entries in that directory.os.path.join(directory, entry_name)
: Correctly constructs the full path to each entry.os.path.isfile(full_entry_path)
: Crucial to check if the entry is a file before trying toopen()
it as such.
Conclusion
The PermissionError: [Errno 13] Permission denied
in Python typically points to one of three main issues:
- Incorrect Path: You're trying to open a directory as a file. Solution: Ensure your path includes the filename and extension.
- Insufficient Permissions: Your script doesn't have the OS-level rights to read/write the target. Solution: Adjust file/folder permissions or run the script with elevated privileges (cautiously).
- File Locked: Another application has the file open exclusively. Solution: Close the file in other programs.
Always verify your file paths, especially distinguishing between files and directories, and use os.path.join()
for constructing paths robustly. If permissions are the issue, consider if running as administrator is appropriate or if file ownership/permissions can be adjusted.