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
- Opening and Reading Files
- Writing and Appending to Files
- Using the with Statement for Files
- Working with File Paths using pathlib