os.listdir unwanted behaviour

Chris Adamson chris.adamson at mcri.edu.au
Tue Sep 29 08:03:46 CEST 2009


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.

Here is my code:

fileList = os.listdir(temporaryDirectory)

for curFile in fileList:
    # print the file list to see if it is indeed growing
    print FileList
    fp = file(os.path.join(temporaryDirectory, "." + curFile), 'w')
    # write stuff

Here is the output:

['a', 'b', 'c']
['a', 'b', 'c', '.a']
['a', 'b', 'c', '.a', '.b']
['a', 'b', 'c', '.a', '.b', '.c']

So the list is growing and eventually curFile iterates through the list 
of files that were created. I don't want this to happen and it seems 
like a bug because the fileList variable should be static, i.e. not 
updated after being assigned.
Even if I assign fileList to another variable this still happens. Any ideas?


More information about the Python-list mailing list