[portland] Not Seeing Script Error(s)

Ethan Furman ethan at stoneleaf.us
Wed Nov 23 00:13:23 CET 2011


Rich Shepard wrote:
> On Tue, 22 Nov 2011, Ethan Furman wrote:
> 
>> They are closed automatically.
> 
>   Ah, so.
> 
>> It's not good practice to do this way, though better would be to assign
>> the open files to their own name, then you could 'name.close()' when you
>> were done.
> 
> Ethan,
> 
>   That's what I thought you did in the lines
> 
> reader = csv.reader(open(filename,"r"),
>                     delimiter="|",
>                     quotechar="'")
> 
> output = csv.writer(open("out.txt","w"),
>                     delimiter="|",
>                     quotechar="'")
> 
>   but reader.close() and output.close() generated python errors.

What's happening there is the two files are being opened, and then those 
open file objects are being handed into the csv.reader and csv.writer 
functions, and the result of the two csv.* calls are being assigned to 
'reader' and 'output'.  Basically, the actual file objects are anonymous.

When reader and output go out of scope they are destroyed, and at that 
point the only references to the two open file objects are lost, and 
then the open file objects are closed by Python.

Like I said, it's better to do it explicity.  ;)

~Ethan~


More information about the Portland mailing list