Need help converting text to csv format

MRAB google at mrabarnett.plus.com
Fri Nov 21 18:26:49 CET 2008


Tim Golden wrote:
> Joe Strout wrote:
>> A follow-up question here... is it really necessary to close things 
>> like files in Python?  I've been slumming it in the REALbasic 
>> community for the last decade, where you generally don't worry about 
>> such things, as any object that represents something "open" will 
>> automatically "close" itself when it dies (and since a closed object 
>> in those cases is useless, I'd rather not have it around after it's 
>> closed anyway). Is the same true in Python, or do we need to 
>> explicitly close things?
> 
> 
> Implementation dependent. (Because it depends on what kind
> of garbage collection or object finalisation happens). Like
> most people, I imagine, in ad-hoc code I'll just do things like:
> 
> <code
> import csv
> 
> writer = csv.writer (open ("data.csv", "wb"))
> writer.writerow (['blah', blah'])
> 
> </code>
> 
> If I exit the interpreter here, I'm pretty much safe.
> But if I add os.startfile ("data.csv"), I'll likely
> get nothing or a file lock.
> 
> I believe that in other implementations -- Jython,
> for example -- you cannot rely on the file closing
> itself.
> 
The file will be closed automatically when the file object is 
garbage-collected.

CPython uses reference-counting, so the file object is garbage-collected 
as soon as there are no references to it.

Jython (and IronPython?) are garbage-collected in the background, so the 
file object is garbage-collected at some point (and you don't know when 
that will be!) when there are no longer any references to it.

> In general in posting public code, especially to
> newcomers, I make the effort to use a try-finally
> or a with statement.
> 



More information about the Python-list mailing list