open() and EOFError
Chris Angelico
rosuav at gmail.com
Mon Jul 7 08:19:20 EDT 2014
On Mon, Jul 7, 2014 at 6:00 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> 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)
Just thought of something. It's possible for input() to raise IOError,
if I'm not mistaken; consider redirection, for instance. In that case,
you would definitely want to split the try blocks, so you don't try to
"handle_bad_file" when no name was entered. (As Dave says, name hasn't
been assigned at that point, although I'd be less concerned about a
possible cascaded NameError than about a possible handle_bad_file()
with the previous name, if this is in a loop.)
ChrisA
More information about the Python-list
mailing list