Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's os.listdir() with os.path.isdir() does not return all directories

Tags:

python

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?

like image 948
lorenzog Avatar asked Sep 11 '25 22:09

lorenzog


1 Answers

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
like image 190
horns Avatar answered Sep 13 '25 11:09

horns