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

Viewed 9302

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.

4 Answers

just use this:

def check_access(file, mode):
   try:
      open(file, mode)
      return True
   except PermissionError:
      return False
print(check_access("test", "w"))

output if no Permission:

False

output if Permission:

True

if you use os.access() then you have a chance of getting something like

   Traceback (most recent call last):
 File "/Users/lawrence/Library/Application Support/CodeRunner/Unsaved/Untitled.py", line 8, in <module>
   open("test", "w").write("test")
 PermissionError: [Errno 13] Permission denied: 'test'

you can still use os.access() but I don't recommend it

Related