liveBook · Manning

With statement

As explained in Python Workout: 50 ten-minute exercises

A Python compound statement that manages one or more context-managed objects and ensures their cleanup when the block exits.

Opening a file creates a resource that should be closed after reading or writing. The with statement places that file in a managed block, binds it to a variable, and guarantees that it is flushed and closed when the block ends. section 5.2 section 5.36

Read a file safely

with open(filename) as f: for one_line in f: print(len(one_line)) The file remains available inside the indented block. Unlike leaving an open file object behind, this form closes the file automatically when the block exits, including after the block has finished writing or iterating. section 5.2

Although files are the common example, with is a general context-manager construct rather than a file-specific feature. A context manager makes an object usable in a with statement; the statement can manage one object or several. section 5.10 section 5.0

Transform one file into another

with open(input_filename) as source, open(output_filename, 'w') as destination: for line in source: destination.write(line.rstrip()[::-1] + '\n') Both files close automatically when the block ends. Closing the output file also flushes its contents, so reading from one file and writing to another avoids the risk of overwriting the input while it is being transformed. section 5.32

Use with when working with files to:

  • Iterate through text files one line at a time instead of loading the entire file into memory. section 5.36
  • Open binary data with a mode such as 'rb', then read byte chunks rather than treating the file as Unicode text. section 5.2
  • Manage separate input and output files while converting formats or filtering records. section 5.22
Table 5.1 What you need to know (view table figure)

Concept

What is it?

Example

To learn more

Files

Overview of working with files in Python

f = open('/etc/passwd')

http://mng.bz/D22R

with

Puts an object in a context manager ; in the case of a file, ensures it’s flushed and closed by the end of the block

with open ('file.text') as f:

http://mng.bz/6QJy

Context manager

Makes your own objects work in with statements

with MyObject() as m:

http://mng.bz/B221

set.update

Adds elements to a set

s.update([10, 20, 30])

http://mng.bz/MdOn

os.stat

Retrieves information (size, permissions, type) about a file

os.stat('file.txt')

http://mng.bz/dyyo

os.listdir

Returns a list of files in a directory

os.listdir('/etc/')

http://mng.bz/YreB

glob.glob

Returns a list of files matching a pattern

glob.glob('/etc/*.conf')

http://mng.bz/044N

Dict comprehension

Creates a dict based on an iterator

{word : len(word)

for word in 'ab cde'.split()}

http://mng.bz/Vggy

str.split

Breaks strings apart, returning a list

# Returns ['ab', 'cd', 'ef']

'ab cd ef'.split()

http://mng.bz/aR4z

hashlib

Module with cryptographic functions

import hashlib

http://mng.bz/NK2x

csv

Module for working with CSV files

x = csv.reader(f)

http://mng.bz/xWWd

json

Module for working with JSON

json.loads(json_string)

http://mng.bz/AAAo

Use the reference table to compare with, context managers, and related file utilities through definitions and short code examples. section 5.0

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains block scope, automatic closing, flushing, multiple managed objects, and binary modes, but defers context-manager implementation details.
Examples
Demonstrates line counting, binary chunk reading, CSV conversion, and reversing lines between separate files.
What it assumes
Assumes familiarity with opening files, iteration, and indentation while teaching context managers through file-based examples.
What you can do after
Apply it via Python file operations to close resources, flush output, and transform data between separate files.
How it connects
Connects with files, context managers, CSV processing, binary file modes, and Python data transformation.

Also explained in

Compare how 6 books explain with statement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.