如何使用Python检查目录的权限?

您可以使用os.access(path,mode)来检查目录权限以及读取,写入和执行权限的模式。为了能够写,您还需要检查执行权限。例如,

>>> import os
>>> os.access('my_folder', os.R_OK) # Check for read access
True
>>> os.access('my_folder', os.W_OK) # Check for write access
True
>>> os.access('my_folder', os.X_OK) # Check for execution access
True
>>> os.access('my_folder', os.X_OK | ox.W_OK) # Check if we can write file to the directory
True

您还可以遵循一个通用的Python习惯用法:寻求宽容比获得许可要容易。按照该习惯用法,您应该尝试写入有问题的目录,如果没有权限,请捕获错误。