Easy question on opening a file

Alex Martelli aleaxit at yahoo.com
Tue Sep 14 07:43:46 EDT 2004


news.west.cox.net <sean.berry2 at cox.net> wrote:
   ...
> >    for file in files:
> >        f1 = file(file, "r")
> >        do some other stuff
> 
> Figured out my mistake already.... 2 minutes later.
> I should not be using the word file, which is a python keyword.

Not a keyword, or else you would have seen a syntax error as soon as you
tried using it as a normal identifier.  Just a built-in name, which
you're perfectly entitle to bind it as an identifier -- but if you do,
of course, then you can't use that same name for two different meanings
in the same scope.  In the call 'file(file, ...", the two occurrences of
identifier 'file' MUST refer to the same object.

It's probably best to avoid using Python builtin's names for other
purposes, of course, as you suggest.  But there are many such names and
you need not memorize them for the purpose -- if your modules and
functions never use some obscure built-in such as, say, 'apply', there's
no harm done if you use that name as an identifier.

A side note: I think you're opening subdirectories as well as files (or
rather, you''re trying to -- the attempt will probably raise an
exception).  You may use a try/except clause to deal with that.


Alex



More information about the Python-list mailing list