an ugly file-reading pattern

Avner Ben avner at skilldesign.com
Mon Apr 14 05:55:05 EDT 2003


"Robin Munn" <rmunn at pobox.com> wrote in message
news:slrnb9h7u4.it3.rmunn at localhost.localdomain...
> Skip Montanaro <skip at pobox.com> wrote:
> > Recent versions of Python (2.2 and later) allow this:
> >
> >     file = file("somefile")
> >     for line in file:
> >         process(line)
>
> Ewww! Don't *do* that! You just shadowed the "file" builtin. Use a
> different name for your file object -- I prefer "input_file":
>
>     input_file = file("somefile")
>     for line in input_file:
>         process(line)

I have tried this shortcut and it works! (This gets rid of naming problem
for good.)

for line in file('/dir/filename.ext'):
         print line

The only problem with this solution is that it leaves the timing of closing
the file undefined. But then, neither of you guys have closed the file
explicitly either!

        Avner.






More information about the Python-list mailing list