os.walk walks too much

Peter Otten __peter__ at web.de
Wed Feb 25 16:07:04 EST 2004


Marcello Pietrobon wrote:

> What is the difference between
> 
>  for dirname in dirs:
>     dirs.remove( dirname )
> 
> and
> 
>  for dirname in dirs[:]:
>     dirs.remove( dirname )

dirs[:] makes a slice containing all elements, i. e. a shallow copy of the
complete list, so the loop is not affected by changes to the original:

>>> dirs = ["alpha", "beta", "gamma"]
>>> dirs == dirs[:] # equal
True
>>> dirs is dirs[:] # but not the same list
False

> def walk_files(root, recursive=False):
>     for path, dirs, files in os.walk(root):
>         for fn in files:
>             yield os.path.join(path, fn)
>             if not recursive:
>                 break
> 
> seems not correct to me:
> 
> because I tend to assimilate yield to a very special return statement
> so I think the following is correct
> 
> def walk_files(root, recursive=False):
>     for path, dirs, files in os.walk(root):
>         for fn in files:
>             yield os.path.join(path, fn)
>         if not recursive:
>             break
> 
> 
> is that right ?

Oops, of course you're right.

Peter




More information about the Python-list mailing list