Python · Errors and files

with

Opens a file and closes it automatically, even when an exception occurs.

Syntax
with open(path) as file:

Example

Open in the lab

More in this group

assert csv module Custom exception else and finally json module pathlib.Path raise try / except

Learn this in the course

Reference pages are the quick answer. The course explains the why, shows the full example and ends with a challenge.

Open the course