Handle PermissionError While Opening a File in Python
The PermissionError in Python occurs when attempting to access or modify a file without the necessary permissions. This can happen when trying to open a read-only file for writing or accessing a restricted system file. To handle this error, we can use exception handling with try-except to catch and manage the PermissionError gracefully.
In this tutorial, we will explore different ways to handle PermissionError with examples.
Examples
1. Handling PermissionError with try-except
To prevent the program from crashing, we use a try-except block to catch PermissionError and display a user-friendly message.
Let us consider the file protected_file.txt that has only read permissions.

main.py
try:
# Attempting to open a file in write mode
with open("protected_file.txt", "w") as file:
file.write("Attempting to write to a protected file.")
except PermissionError:
print("Error: You do not have permission to modify this file.")
Explanation:
In this example:
- The program attempts to open
protected_file.txtin write mode usingopen(). - If the file is read-only or requires elevated permissions, Python raises a
PermissionError. - The
except PermissionErrorblock catches the error and prints a user-friendly message.
Output:

2. Checking File Permissions Before Accessing
We can use the os.access() function to check whether the file has write permission before attempting to open it.
main.py
import os
file_path = "/system/protected_file.txt"
# Checking if the file has write permission
if os.access(file_path, os.W_OK):
with open(file_path, "w") as file:
file.write("Writing to a file after permission check.")
print("File updated successfully.")
else:
print("Error: You do not have write permissions for this file.")
Explanation:
- The script checks if the file at
file_pathhas write permission usingos.access(file_path, os.W_OK). - If the file is writable, it proceeds with opening and writing to it.
- If the file is not writable, it prints an appropriate error message and avoids raising
PermissionError.
Output:
Error: You do not have write permissions for this file.
3. Handling PermissionError When Deleting a File
Sometimes, attempting to delete a file without sufficient permissions raises PermissionError. We handle this using try-except.
main.py
import os
file_path = "/system/protected_file.txt"
try:
os.remove(file_path)
print("File deleted successfully.")
except PermissionError:
print("Error: You do not have permission to delete this file.")
Explanation:
- The script attempts to delete
file_pathusingos.remove(). - If the file requires elevated privileges for deletion,
PermissionErroris raised. - The
except PermissionErrorblock catches the error and prints an appropriate message.
Output:
Error: You do not have permission to delete this file.
4. Running Script with Elevated Permissions
For situations where administrator or root access is required, we can check if the script has necessary privileges and request the user to run it with elevated permissions.
main.py
import os
import sys
# Checking if the script is running with administrator privileges
if os.name == "nt": # Windows
import ctypes
if not ctypes.windll.shell32.IsUserAnAdmin():
print("Error: Please run the script as administrator.")
sys.exit(1)
else: # Linux/Mac
if os.geteuid() != 0:
print("Error: Please run the script as root.")
sys.exit(1)
# Trying to open a restricted file
try:
with open("/etc/shadow", "r") as file:
print("File opened successfully.")
except PermissionError:
print("Error: Insufficient permissions to read the file.")
Explanation:
- On Windows,
ctypes.windll.shell32.IsUserAnAdmin()checks if the script has administrator privileges. - On Linux/Mac,
os.geteuid()checks if the script is running as root. - If not, the script requests the user to run it with elevated privileges.
Output:
Error: Please run the script as administrator.
Conclusion
Concluding this tutorial, here are key strategies to handle PermissionError in Python:
- Use
try-exceptto catch and handlePermissionError. - Check file permissions with
os.access()before accessing. - Ensure the script runs with appropriate privileges when needed.
