os.listdir unwanted behaviour
Peter Otten
__peter__ at web.de
Tue Sep 29 03:15:30 EDT 2009
Chris Adamson wrote:
> I am writing code that cycles through files in a directory and for each
> file it writes out another file with info in it. It appears that as I am
> iterating through the list returned by os.listdir it is being updated
> with the new files that are being added to the directory. This occurs
> even if I reassign the list to another variable.
My guess is that this has nothing to do with os.listdir():
>>> import os
>>> files = os.listdir(".")
>>> files
['b', 'a']
>>> os.system("touch c")
0
>>> files
['b', 'a'] # look Ma, no automatic updates!
>>> os.listdir(".")
['b', 'c', 'a']
It is normal Python behaviour that assignment doesn't copy a list; it just
creates another reference:
>>> a = [1]
>>> b = a
>>> id(a) == id(b)
True
>>> b.append(2)
>>> a
[1, 2]
Use slicing to make an actual copy:
>>> b = a[:] # b = list(a) would work, too
>>> id(a) == id(b)
False
>>> b.append(3)
>>> a
[1, 2]
>>> b
[1, 2, 3]
> Here is my code:
No, it's not. If you post a simplified version it is crucial that you don't
remove the parts that actually cause the undesired behaviour. In your case
there has to be a mutating operation on the list like append() or extend().
Peter
More information about the Python-list
mailing list