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"
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.")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:
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}).")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"
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.