我正在(向上)遍历目录树,我需要找到所有目录。但是 os.listdir()
的输出, 当与 os.path.isdir()
组合时不是我所期望的。
例如,这只显示了两个目录(bin
和 dev
):
$ python
Python 2.7.9 (default, Mar 1 2015, 12:57:24)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> for d in os.listdir('/'):
... if os.path.isdir(d):
... print d
...
bin
dev
>>>
但是,删除 os.path.isdir()
调用会列出所有条目,包括文件和目录:
>>> for d in os.listdir('/'):
... print d
...
sbin
home
initrd.img
[...]
run
sys
>>>
令人惊讶的是,在第一个代码段未列出的目录上运行isdir
返回True:
>>> os.path.isdir('/run')
True
>>>
我错过了什么?
最佳答案
您的os.path.isdir
正在检查该目录是否存在于当前 目录下,而不是os.listdir
列出的目录('/'
).
试试这个:
for d in os.listdir('/'):
if os.path.isdir(os.path.join('/', d)):
print d
关于带有 os.path.isdir() 的 Python os.listdir() 不返回所有目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33090642/