How to Check If a File Is Writable in Python
Before attempting to write data to a file, it is important to verify that your program has the necessary permissions. Writing to a read-only file or a protected system file will raise a PermissionError (Errno 13) and crash the script if not handled.
This guide explains how to check file writability using os.access() (Look Before You Leap) and exception handling (Easier to Ask for Forgiveness than Permission).
Method 1: Using os.access() (Pre-Check)
The os.access() function allows you to query the filesystem for permissions before performing an operation. Pass os.W_OK to check for writability.
import os
file_path = "config.txt"
# ✅ Check if file exists AND is writable
if os.path.exists(file_path):
if os.access(file_path, os.W_OK):
print(f"'{file_path}' is writable.")
else:
print(f"'{file_path}' is read-only or locked.")
else:
print(f"'{file_path}' does not exist.")
Race Condition Risk: Between the moment you check os.access() and the moment you actually open the file, permissions could change (e.g., another process locks the file). Relying solely on os.access is not thread-safe.
Method 2: Using Exception Handling (Recommended)
The most robust way to check if a file is writable is to simply try writing to it. If it fails, catch the error. This avoids race conditions and handles all edge cases (disk full, file locked, permissions).
file_path = "system.log"
try:
# ✅ Try to open in append mode to check writability without deleting content
with open(file_path, "a") as f:
pass # Do nothing, just checking if open() succeeds
print("File is writable.")
except PermissionError:
print("Error: Permission denied. File is read-only.")
except IOError as e:
print(f"Error: Unable to write to file ({e}).")
Opening in 'a' (append) mode preserves existing content. Opening in 'w' mode would truncate (erase) the file immediately upon opening, which is destructive if you are only checking permissions.
Checking if a Directory is Writable
Sometimes the file doesn't exist yet, and you need to check if you have permission to create it in a specific folder.
import os
directory = "/var/logs"
# ✅ Check if the directory allows writing (creating new files)
if os.access(directory, os.W_OK):
print(f"Directory '{directory}' is writable.")
else:
print(f"Cannot create files in '{directory}'.")
Conclusion
To safely check for writability:
- Use
try-except PermissionErrorwhen you are ready to write. This is the most reliable method. - Use
os.access(path, os.W_OK)for quick status checks (e.g., disabling a "Save" button in a UI) but generally not for core logic due to race conditions. - Check directories if the file does not exist yet to ensure creation is allowed.