open() and EOFError
Chris Angelico
rosuav at gmail.com
Mon Jul 7 09:29:09 EDT 2014
On Mon, Jul 7, 2014 at 11:06 PM, Mark Lawrence <breamoreboy at yahoo.co.uk> wrote:
>> try:
>> name = input("Enter file name, or Ctrl-D to exit")
>> # On Windows, use Ctrl-Z [enter] instead.
>> except EOFError:
>> sys.exit()
>> try:
>> fp = open(name)
>> except IOError:
>> handle_bad_file(name)
>> else:
>> handle_good_file(fp)
>>
>
> All those extra lines to type, not on your life. Surely it would be better
> written as a one liner?
In all seriousness, though, if you're worried about the number of
lines, it's not that big a deal to squish up the small try blocks.
try: name = input("Enter file name, or Ctrl-D to exit")
except EOFError: sys.exit()
try: fp = open(name)
except IOError: handle_bad_file(name)
else: handle_good_file(fp)
Might violate some style guides, but IMO it's not a problem.
ChrisA
More information about the Python-list
mailing list