with statement
A statement that sets something up, runs a block, and guarantees the matching clean-up afterwards, most often closing a file.
In more detail
with open(name) as f: closes f when the block ends, even if an exception is raised inside it, so you can never forget the close. The object after with is a context manager.
Example
with open("notes.txt", encoding="utf-8") as f:
text = f.read()Related terms
- file object — The object returned by open() that you read from or write to, and close when finished.
- close() — The file method that finishes with a file, writing out any buffered data and freeing it for other programs.
- finally clause — The last part of a try statement, which always runs, whether the try block succeeded, failed or returned early.
Taught in
- Paths And Files The Modern Way — Hands-on Python: Complete Video Course & Book
- JSON And CSV — Hands-on Python: Complete Video Course & Book
- Testing With pytest — Hands-on Python: Complete Video Course & Book
- Import Variants, dir() And sys.path — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Your Own Modules And Packages — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Modules Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Introspection: hasattr, __name__, __module__ And __bases__ — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Streams, Handles And Open Modes — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- read, readline, errno And bytearray — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Comprehensions, Closures And Files Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep