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?

0

1 Answer 1

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 ...

Sign up to request clarification or add additional context in comments.

2 Comments

this does not look very elegant
thats only because you see the implementation ... if you just do from util import safe_open ... then use it. then its pretty elegant ... (

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.