June 2019
Beginner to intermediate
770 pages
19h 24m
English
Contexts and context managers are used in several places in Python. We'll look at a few examples to establish the basic terminology.
Python defines context using the with statement. The following program is a small example that parses a log file to create a useful CSV summary of that log. Since there are two open files, this will use the nested with contexts. The example uses a complex regular expression, format_1_pat. We'll define this shortly.
We might see something similar to the following in an application program:
from pathlib import Pathimport gzip import csv source_path = Path.cwd()/"data"/"compressed_data.gz"target_path = Path.cwd()/"data"/"subset.csv"with target_path.open('w', newline='') ...Read now
Unlock full access