open() and EOFError

Mark Lawrence breamoreboy at yahoo.co.uk
Mon Jul 7 09:06:33 EDT 2014


On 07/07/2014 09:09, Chris Angelico wrote:
> 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)
>
> It seems trivial in this example to break it into two try blocks:
>
> 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?

-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection is active.
http://www.avast.com





More information about the Python-list mailing list