I'm traversing a directory tree (upwards) and I need to find all directories. However the output of os.listdir()
, when combined with os.path.isdir()
is not what I would expect.
For example, this only shows two directories (bin
and 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
>>>
However, removing the os.path.isdir()
call lists all entries, both files and directories:
>>> for d in os.listdir('/'):
... print d
...
sbin
home
initrd.img
[...]
run
sys
>>>
The surprising bit is that running isdir
on a directory that is not listed by the first snippet returns True:
>>> os.path.isdir('/run')
True
>>>
What am I missing?
Your os.path.isdir
is checking if the directory exists under the current directory, not the directory that os.listdir
is listing ('/'
).
Try this:
for d in os.listdir('/'):
if os.path.isdir(os.path.join('/', d)):
print d
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With