open() and EOFError

Dave Angel davea at
Mon Jul 7 14:14:31 CEST 2014

Steven D'Aprano <steve at> Wrote in message:
> On Mon, 07 Jul 2014 17:04:12 +1200, Gregory Ewing wrote:
>> Steven D'Aprano wrote:
>>> Are there any circumstances where merely *opening* a file (before
>>> reading it) can raise EOFError?
>> I don't think so. As far as I know, the only built-in thing that raises
>> EOFError is input() (and raw_input() in Py2).
> Thanks. That's what I thought.
> How do people feel about code like this?
> try:
>     name = input("Enter file name, or Ctrl-D to exit")
>     # On Windows, use Ctrl-Z [enter] instead.
>     fp = open(name)
> except EOFError:
>     sys.exit()
> except IOError:
>     handle_bad_file(name)
> else:
>     handle_good_file(fp)

Depends on who is going to be maintaining your code next year.Be
 sure and leave him some comments. Even if it's going to be you.

For example,  it's not obvious at a glance that name is visible in
 the second exception block and not the first. 


More information about the Python-list mailing list