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?