Sep-16-2019, 01:44 AM
(Sep-15-2019, 10:11 PM)hshivaraj Wrote: Is approach1 is better approach 2Both work in this case,approach 2 you can modify the error message.
It's not unclear what happen here in the case without try,except.
def _open(config): with open(config, "r") as fh: return fh.read()
>>> _open('foo.txt') 'hello' >>> _open('foo999.txt') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "file_try.py", line 3, in _open with open(config, "r") as fh: FileNotFoundError: [Errno 2] No such file or directory: 'foo999.txt' [Errno 2] No such file or directory: 'foo999.txt'Shorter just print the error from last line over.
def _open(config): try: with open(config, "r") as fh: return fh.read() except OSError as err: print(err)
>>> _open('foo.txt') 'hello' >>> _open('foo999.txt') [Errno 2] No such file or directory: 'foo999.txt'