2

A simple way to open a file and read its contents is using with:

with open ('file.txt', "r") as filehandle:
    contents = filehandle.read()

But that does not include excepting file opening errors in a way that a try/except would:

try:
    filehandle = open('file.txt', 'r')
    contents = filehandle.read()
except IOError:
    print('There was an error opening the file!')
    sys.exit()

Is there a way to integrate a failure message in the with statement so that it exits gracefully if the opening fails that would be done in fewer lines of code than the second example yet provide the same functionality? If not that, is there anything more elegant (or minimalist) than the second form?

amphibient
  • 29,770
  • 54
  • 146
  • 240

1 Answers1

0
from contextlib import contextmanager

@contextmanager
def safe_open(fname,mode):
    try:
        fh = open(fname,mode)
    except IOError:
        print "ERROR OPENING FILE :",fname
        sys.exit()
    else:
        yield fh
        try:
            fh.close()
        except:
            pass


with safe_open("nofile","rb") as f:
    f.write("blah")

Im not sure that its more elegant but meh ...

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179