python - 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?
解决方案
推荐阅读
- javascript - 如何避免缩进嵌套承诺?
- ios - Swift:如何在不显式使用 CGRect 的情况下为 UIView 或 CALayer 的每个角设置不同的半径?
- c++ - 为什么在将唯一指针插入无序映射时 C++ 会给我一个错误?
- python - 检索具有多个条件的值 - 熊猫
- string - 错误:在 C++ 中从“char”转换为非标量类型“std::string {aka std::basic_string}”
- javascript - 调整图像大小并保持叠加位置
- c# - 如何为每个 PictrueBox 单独使用方法
- javascript - Nuxt 中的 Tailwind PostCss 配置
- c - 国际象棋程序知道女王什么时候可以俘虏国王
- javascript - 在 javascript 中创建日历