Python › File I/O & Context Managers

How do you open and read a text file using the 'with' statement, and why is 'with' preferred over manual open()/close()?

Beginner

Answer

'with open(path) as f:' guarantees the file is properly closed when the block exits, EVEN IF an exception occurs inside it — manually calling open() and close() risks leaking the file handle if an exception happens between them and close() is never reached.
with open("data.txt") as f:
    content = f.read()
print(content)
# file is automatically closed here, even if .read() had raised an exception
Real-world example Reading a configuration or data file safely, guaranteeing the file handle is released even if reading fails partway through.

Common follow-ups: What exception type does open() raise if the specified file doesn't exist?