A with statement opens a file for a block and closes it automatically when processing finishes. It makes resource handling shorter and easier to read than manually calling close(). section 5.1.4
Reading NFL statistics
with open('nfl_offensive_stats.csv', 'r') as f: data = list(csv.reader(f)) The block reads the CSV data, processes quarterback passing yards, and then closes the file automatically. An exercise asks you to convert equivalent code that opens and closes the file manually. section 5.1.4 section 5.2
def print_quarterbacks():
nfl_file = open('nfl_offensive_stats.csv')
for line in nfl_file:
lst = line.split(',')
if lst[2] == 'QB':
print(f"{lst[3]}: {lst[7]} passing yards")
nfl_file.close()
Compare manual file closing with the equivalent with-statement structure. section 5.2





