0Pricing
Python Academy · Lesson

Using the with Statement for Files

Ensure files are closed automatically using context managers.

Introduction

The with statement ensures files are closed automatically, even if an exception occurs.

The with Statement

with open('file.txt') as f: ... automatically closes f when the block exits, whether normally or via exception.
# with open('data.txt') as f:
#     content = f.read()
# f is now closed
print('with demo')

All lessons in this course

  1. Opening and Reading Files
  2. Writing and Appending to Files
  3. Using the with Statement for Files
  4. Working with File Paths using pathlib
← Back to Python Academy