Check if I can write a file to a directory or not with Python

prosseek picture prosseek · Sep 12, 2010 · Viewed 7.4k times · Source

I need to check if I can write a file to a directory that user point to with Python.

Is there an way to check it in advance? I may be using try .. catch for this purpose, but I expect something better in the sense that I can check in advance.

Answer

user79758 picture user79758 · Sep 12, 2010

Despite Jim Brissom's claim, exception handling is not cheap in Python compared to 'check then try' idioms if you expect the thing to fail more than a few percent of the time. (Read to the end for an exception!) However, the key thing here is that you need to check the exception anyway, because the permissions can change between the check and your write:

### !!! This is an example of what not to do!
### !!! Don't do this!
if os.access("test", os.W_OK):
    # And in here, some jerk does chmod 000 test
    open("test", "w").write(my_data)
    # Exception happens despite os.access!

os.access and the stat module are great if you're trying to, e.g., prepare a list of folders for the user to pick and want to exclude invalid ones a priori. However, when the rubber hits the road, it is not a replacement for exception handling if you want your program to be robust.

And now the exception to the exceptions-are-slow rule: Exceptions are slow, but disks are slower. And if your disk is under particularly heavy load, you might end up having the file you're interested in evicted from the OS or disk cache between the os.access and open call. In this case, you're going to experience a major slowdown as you have to go to disk (and these days, that can also mean network) twice.