Optimizing tips for os.listdir

Peter Hansen peter at engcorp.com
Mon Sep 27 15:36:42 EDT 2004


Bengt Richter wrote:
> But it seems like you are asking the os to chase through full paths at
> every isdir operation, rather than just telling it to make its current working
> directory the directory you are interested in and doing it there. E.g., (untested)
> 
>     savedir = os.getcwd()
>     os.chdir(path)
>     dirs = [opj(path, p) for p in os.listdir('.') if oisd(p)]
>     os.chdir(savedir)

One aspect of this which needs mentioning is that it could
cause incorrect behaviour of other parts of the application
if there are multiple threads relying on using the current
working directory... the CWD is global to the application, AFAIK.

-Peter



More information about the Python-list mailing list