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.