os.path.walk oddity

Fredrik Lundh fredrik at pythonware.com
Thu Feb 15 03:07:26 EST 2001


Simon Callan wrote:
> def toRiscos(arg, dir, names):
>   temp = names

this assignment doesn't make a copy, it just adds
another reference to the "names" array.

>   count = 0
>   for file in temp:

same thing as iterating over names.

>     root, ext = os.path.splitext(file)
>     if ext == '.c':
>       del names[count]

here you're modifing the array you're looping over.
that's bad.

>       rename(dir, root, 'c')
>     elif ext == '.h':
>       del names[count]
>       rename(dir, root, 'h')
>     count += 1

two possible solutions: change the loop to

    for file in names[:]:

or get rid of the del statements.  for-in won't
loop over an item more than once anyway...

Cheers /F





More information about the Python-list mailing list