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)
| 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 |
|||
| Retrieves information (size, permissions, type) about a file |
|||
Use the reference table to compare with, context managers, and related file utilities through definitions and short code examples. section 5.0





