Check If A File is Writable in Python
Last Updated :
24 Apr, 2025
When it comes to Python programming it is essential to work with files. One important aspect is making sure that a file can be written before you try to make any changes. In this article, we will see how we can check if a file is writable in Python.
Check If a File Is Writable in Python
Below are some of the ways by which we can check if a file is writable in Python:
- Using os.access() Function
- Verifying Writability
- Using the file object's writable() method
Using the os.access() Function
This method is more useful to check if the given file is writable, and whether the matter file exists or not. It uses the os.access() function that inquires about the permissions of the specified file, from the operating system.
Python3
import os
# Replace with the actual file path
file_path = "C:/Users/Pankaj Kumar Bind/Downloads/Test.txt"
try:
# Check if the file is writable using os.access()
if os.access(file_path, os.W_OK):
print(f"File '{file_path}' is writable.")
else:
print(f"File '{file_path}' is not writable.")
except FileNotFoundError:
print(f"File '{file_path}' does not exist.")
except PermissionError:
print(f"You don't have permission to access or write to '{file_path}'.")