Check If A File is Writable in Python
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.
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}'.")
Output:
Verifying Writability
This approach follows Python conventions and this is more succinct especially when working with existing files. It tries to open the file in mode ("w") and verifies if a PermissionError exception occurs.
import os
# Replace with the actual file path
filepath = "C:/Users/Pankaj Kumar Bind/Desktop/test.txt"
def isFileWritable(filepath):
"""Checks if a file is writable by attempting to open it in write mode.
Args:
filepath (str): The path to the file.
Returns:
bool: True if the file is writable, False otherwise.
"""
try:
with open(filepath, "w") as f:
# Write something to verify writability
f.write("Test")
return True
except PermissionError:
return False
if isFileWritable(filepath):
print(f"{filepath} is writable.")
else:
print(f"{filepath} is not writable.")