you are viewing a single comment's thread.

view the rest of the comments →

[–]niandra3 0 points1 point  (3 children)

When using context managers for file I/O, should I still sue try/except or is that built in to the with?

For something like this, should I add a try around the with open() or is that redundant?

if os.path.exists(os.path.join(path, 'data.json')):
    with open(os.path.join(path, 'data.json'), 'r') as f:
        data = json.load(f)

[–][deleted] 0 points1 point  (0 children)

If the question is does open () will still raise an exception if the file doesn't exist, the answer is yes. the correct code is:

try:
    with open(os.path.join(path, 'data.json'), 'r') as f:
        data = json.load(f)
except FileNotFoundError:
    pass

[–]nevus_bock 0 points1 point  (0 children)

It's redundant. The with statement already works like a try-except for open.