奇怪的行为os.path.isdir(x)
我只想获取当前目录的目录列表(无递归)。
另外,我有挂载点/mnt/test0带ext4。
我愿意:
>>> [x for x in os.listdir('/mnt/test0/base/trash') if os.path.isdir(x)]
[]
/mnt/test0/base/trash有一个 dir test,但是list是空的。
如果我做:
>>> [x for x in os.listdir('/mnt/test0/base/trash')]
它在这里。
>>> [x for x in os.listdir('/mnt/test0/base/trash')]
['test']
Linux ls:
# ls -lA
total 28
drwxrwx--- 9 root root 28672 Nov 11 23:00 test
什么是奇怪的错误os.path.isdir(x)?
更新:
我重新启动 Python,现在我得到了结果:
>>> [x for x in os.listdir('/mnt/test0/base/trash') if os.path.isdir(x)]
['test']
这很奇怪。
回答
问题是os.listdir只列出了路径的最后部分。请注意它如何返回['test']而不是['/mnt/test0/base/trash/test']。
当您使用 进行检查时isdir(),名称是相对于当前工作目录而不是相对于 进行评估的/mnt/test0/base/trash。基本上你需要这样的东西:
>>> d = '/mnt/test0/base/trash'
>>> [x for x in os.listdir(d) if os.path.isdir(os.path.join(d, x))]
- @Kirill it will depend on where you run the code from (i.e. you current working directory). Your original code should work fine if you run it from within `/mnt/test0/base/trash` and fail everywhere else.