os.listdir unwanted behaviour

Chris Rebert clp2 at rebertia.com
Tue Sep 29 02:40:40 EDT 2009


On Mon, Sep 28, 2009 at 11:03 PM, Chris Adamson
<chris.adamson at mcri.edu.au> 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()
>
> 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?

Copy the list instead? Python uses call-by-object, so assignment to a
variable doesn't cause copying, you must do so explicitly:

fileList = os.listdir(temporaryDirectory)[:]

Although this behavior (bug?) you're running into definitely seems
like ought to be mentioned in the docs. File a bug perhaps?

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list