首页 > 解决方案 > Check if directory has read/write permissions

问题描述

My environment is Python 3.7.2, running on Windows 10.

I am working on some downloader. First of all I want to check if directory where I want to download files has read / write permissions:

I tried two ways:

1 code:

Using os module (os.access function) to check access, returns True even if I have no write access. Module gives wrong results on Windows:

# check for read/write access
if not os.access(path, os.W_OK):
    raise PermissionError("Path %s, doesn't have WRITE permissions" % path)
# check for write access
if not os.access(path, os.R_OK):
     raise PermissionError("Path %s, doesn't have READ permissions" % path)

2 code:

The idea to use tempfile.TemporaryFile() seemed clean way to check directory permission, with no risk of leaving junk files on the system. The problem is, tempfile.TemporaryFile() hangs on my system when it's given a dir parameter that hasnt any permissions,script won't continue to execute or exit. nothing is returned. it's just stuck at that line . The bug affects only Windows environments, but unfortunately it has the result of rendering tempfile.TemporaryFile unusable on Windows for this common use case:

import tempfile
import errno

try:
    testfile = tempfile.TemporaryFile(dir = path)
    testfile.close()
except (OSError, IOError) as e:
    if e.errno == errno.EACCES or e.errno == errno.EEXIST:
        raise PermissionError("Path %s, doesn't have READ/WRITE permissions" % path)

Anyone has idea how to check permissions of a directory?

标签: pythondirectory

解决方案


推荐阅读