an ugly file-reading pattern

Jp Calderone exarkun at intarweb.us
Mon Apr 14 13:47:16 EDT 2003


On Mon, Apr 14, 2003 at 06:53:32PM +0200, Avner Ben wrote:
> 
> "Robin Munn" <rmunn at pobox.com> wrote in message
>
> > You're right, I didn't close the file explicitly. But explicit is better
> > than implicit, so IMHO it's better to give a name to the file object so
> > that you can close it explicitly:
> >
> >     input_file = file("somefile")
> >     for line in input_file:
> >         process(line)
> >     input_file.close()
> 
> 
>     The C# language has a nice construct: using (variable = whatever) { /*
> code */ }. The variable in the using header is guaranteed to be
> garbage-collected at the end of the block (or so I think). Could be useful
> here.
> 

  In CPython, the reference count to the file object in:

    for line in file(...):
        ...

  will drop to 0 immediately after the loop, and the file will be closed at
that point.

  Jp

-- 
In the days when Sussman was a novice Minsky once came to him as he sat
hacking at the PDP-6. "What are you doing?" asked Minsky. "I am training a
randomly wired neural net to play Tic-Tac-Toe." "Why is the net wired
randomly?" asked Minsky. "I do not want it to have any preconceptions of how
to play." Minsky shut his eyes. "Why do you close your eyes?" Sussman asked
his teacher. "So the room will be empty." At that moment, Sussman was
enlightened.
 -- 
 up 25 days, 13:02, 2 users, load average: 2.04, 2.02, 2.00





More information about the Python-list mailing list