python os.listdir 遇到 OSError : [Errno 13] Permission denied

标签 python python-2.7 python-os

我正在尝试使用 os.listdir 获取子目录列表,但当我缺乏这些子目录之一的权限时遇到问题。我无法获得许可,所以我想尽可能优雅地继续。理想情况下,我能够忽略我无权访问的任何目录并返回任何其他目录,以免错过任何子目录。

我尝试过使用 os.walk,但遇到了许多其他问题(包括性能),因此决定不使用它。

举个例子。根目录中有3个子目录,a,b,c

root dir
|
----> dir a 
|
----> dir b
|
----> dir c

我有a和c的权限,但没有b(提前不知道)。我想返回 [a, c]

这是带有一些概括的代码-

def get_immediate_subdirectories(directory):
"""Returns list of all subdirectories in
directory

Args:
  directory: path to directory

Returns:
  List of child directories in directory excluding 
  directories in exclude and any symbolic links

"""
exclude = ["some", "example", "excluded", "dirnames"]
sub_dirs = []
try:
    all_files = os.listdir(directory)
except OSError:
    # **Ideally I'd be able to recover some list here/continue**
for name in all_files:
    if name in exclude:
        continue
    full_path = os.path.join(directory, name)
    if os.path.isdir(full_path):
        # Keep these separate to avoid issue
        if not os.path.islink(full_path):
            sub_dirs.append(name)
return sub_dirs

最佳答案

此问题中所做的假设 - 目录中的不可读条目可能会导致 os.listdir() 失败,并且可能会出现由其他条目组成的部分结果 - - 是假的。

观察:

>>> import os
>>> os.mkdir('unreadable.d')
>>> os.chmod('unreadable.d', 0)
>>> result = os.listdir('.')
>>> print result
['unreadable.d']

它只是尝试在不可读的目录本身上运行 listdir() 失败:

>>> os.listdir('unreadable.d')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 13] Permission denied: 'unreadable.d'

关于python os.listdir 遇到 OSError : [Errno 13] Permission denied,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42444822/

相关文章:

python - 计算每个符号在字符串中出现的次数 - python

python - 使用 % 字典格式化多行字符串

python - tshark提供的原始数据是否完整?

python - 如何在 Flask 应用程序模型中添加带有值(预定义)的下拉菜单?

python-2.7 - 使用python连接ftp服务器

python - 如何执行另一个python文件然后关闭现有的文件?

python - macOS - os.listdir 返回以 "."开头的双项?

python - 在 Python 中删除/启用根权限打开文件

python - FigureCanvasTkAgg 的声明导致内存泄漏