Optimizing tips for os.listdir

Kjetil Torgrim Homme kjetilho at yksi.ifi.uio.no
Mon Sep 27 20:53:05 EDT 2004


[Nick Craig-Wood]:
>
>   [Thomas]:
>   >
>   > I'm doing this :
>   >
>   > [os.path.join(path, p) for p in os.listdir(path) \
>   >                            if os.path.isdir(os.path.join(path, p))]
>
>   Under a unix based OS the above will translate to 1
>   opendir()/readdir()/closedir() and 1 stat() for each file.  There
>   isn't a quicker way in terms of system calls AFAIK.

there's a well known trick for Unix file systems[1]:

if a directory has a link count of exactly 2, there are no
subdirectories.  if there was a subdirectory, it would contain a ".."
refering to its parent, thereby raising the parent's link count to 3.

(it's not clear to me whether this is helpful for the OP, though.)


[1] the behaviour is not mandated by POSIX.  e.g., a mounted ISO
    9660-file system will not necessarily obey this "rule".  GNU find
    relies on it unless you explicitly specify "-noleaf", so it works
    pretty well in practice.
-- 
Kjetil T.



More information about the Python-list mailing list