os.listdir unwanted behaviour

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Sep 29 09:17:24 CEST 2009


On Tue, 29 Sep 2009 16:03:46 +1000, Chris Adamson wrote:

> Hello,
> 
> 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
>     fp.close()

Are you sure this is your code you're using? Where is FileList defined? 
It's not the same as fileList.

What you describe is impossible -- os.listdir() returns an ordinary list, 
it isn't a lazy iterator that updates automatically as the directory 
changes. (At least not in Python2.5 -- I haven't checked Python 3.1.) 
This is what happens when I try it:


>>> import os
>>> os.listdir('.')
['a', 'c', 'b']
>>> filelist = os.listdir('.')
>>> for curFile in filelist:
...     print filelist
...     fp = file(os.path.join('.', "."+curFile), 'w')
...     fp.close()
...
['a', 'c', 'b']
['a', 'c', 'b']
['a', 'c', 'b']


I think the bug is in your code -- you're probably inadvertently updating 
fileList somehow.



-- 
Steven



More information about the Python-list mailing list