open() and EOFError

Steven D'Aprano steve at pearwood.info
Mon Jul 7 10:00:14 CEST 2014


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)



-- 
Steven



More information about the Python-list mailing list