an ugly file-reading pattern

Skip Montanaro skip at
Mon Apr 14 15:57:02 CEST 2003

    Avner> "Robin Munn" <rmunn at> wrote in message
    Avner> news:slrnb9h7u4.it3.rmunn at localhost.localdomain...
    >> Skip Montanaro <skip at> 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":

Yes, as I replied to Christian's post, I had one foot in the boat and one on
the dock.  "file" shouldn't have been a variable name.  This would have
worked fine:

    for line in file("somefile"):

presuming you want to slurp the entire file in that one loop (otherwise you
should assign the file object to a variable, just not to a variable named
"file" ;-).


More information about the Python-list mailing list