Home » Programming » Python » Python Check File Directory Writable

Best Way to Check if a File/Directory is Writable [Python]

This quick tip will show you the best way to check if a file or directory is writable in the Python programming language.

Python: The Best Way To Check if a File or Directory is Writable

Just try and write to it.

That’s it. If you can write to the file, it must be writable

Try and write to it, and handle any failure which occurs.

try:
    with open('newfile.txt', 'w') as file
        file.write('hello!')
        file.close()
except IOError as error: # You could also catch Exception instead of IOError to check for problems but this may be casting too-wide a net
    # The file was not accessible for some reason
    # Do something here to alert the user or perform another action instead
    print(error)
     # The error itself may include information about why the file write failed
    if x.errno == errno.EACCES:
        print('No permission to write to file)
    elif x.errno == errno.EISDIR:
        print('Cannot write to file - a directory with that name exists')

The Other Ways

We have covered several ways to check if a file is readable.

Some of these, such as using os.access and os.exists, can also be used in combination to check if a file is writable. Unfortunately, these methods are complex to code and never guaranteed to work.

Different filesystems behave differently when reporting whether a file can be written, and there are other factors (like the file being accessed by another program the moment you happen to be trying to write to it) that may cause a check on writability to fail where it should succeed or the opposite.

To be sure, it’s best to try and write to the file and ask for forgiveness later by catching an error if you can’t.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment