Check if File is Writable in Python

Python – Check if file is writable

To check if a file is writable or not in Python, you can use the os library. Import os library, call the os.access() function and pass the file path and mode (os.W_OK, to check if file is writable) as arguments.

The syntax to call os.access() function to check if a file is writable is

os.access('path/to/file', os.W_OK) == 0

The function call returns a boolean value of True if the file is writable, or False if the file is not writable.

Note: The 'path/to/file' in the above expression should be replaced with the actual path of the file, including the file name, you want to check.

Example

In the following program, we check programmatically if the file myfolder/sample.txt is writable or not.

File

Python - Check if file is writable

Python Program

import os

path_to_file = "myfolder/sample.txt"

if os.access(path_to_file, os.W_OK):
    print("File is writable.")
else:
    print("File is not writable.")
Copy

Output

File is writable.

Summary

In this tutorial of Python Examples, we learned how to check if a file is writable or not by using os.access() function.

Related Tutorials

Code copied to clipboard successfully 👍