Determining Whether a Directory is Writeable

前端 未结 10 1935
萌比男神i
萌比男神i 2020-12-07 14:44

What would be the best way in Python to determine whether a directory is writeable for the user executing the script? Since this will likely involve using the os module I sh

10条回答
  •  忘掉有多难
    2020-12-07 14:50

    My solution using the tempfile module:

    import tempfile
    import errno
    
    def isWritable(path):
        try:
            testfile = tempfile.TemporaryFile(dir = path)
            testfile.close()
        except OSError as e:
            if e.errno == errno.EACCES:  # 13
                return False
            e.filename = path
            raise
        return True
    

    Update: After testing the code again on Windows I see that there is indeed an issue when using tempfile there, see issue22107: tempfile module misinterprets access denied error on Windows. In the case of a non-writable directory, the code hangs for several seconds and finally throws an IOError: [Errno 17] No usable temporary file name found. Maybe this is what user2171842 was observing? Unfortunately the issue is not resolved for now so to handle this, the error needs to be caught as well:

        except (OSError, IOError) as e:
            if e.errno == errno.EACCES or e.errno == errno.EEXIST:  # 13, 17
    

    The delay is of course still present in these cases then.

提交回复
热议问题