Use a with statement when a block should run while Python manages a resource. For files, it binds opened objects to variables and closes them automatically when the block ends. section 6.3 section 6.9
Apply the construct to common file-processing tasks:
- Manage several files in one statement, such as an input file opened for reading and an output file opened for writing. section 6.19
- Iterate through an input file, transform each line, and write results without explicitly calling close(). section 6.27
- Prefer separate input and output files when rewriting content, avoiding accidental overwrites associated with editing the same file in r+ mode. section 6.27
- Use the same pattern with structured file workflows involving csv readers and writers or JSON data. section 6.19 section 6.30
Reverse every input line
with open('input.txt') as source, open('output.txt', 'w') as target: for line in source: target.write(line.rstrip()[::-1] + '\n') Both files are closed when the indented block ends; the output file is flushed as it closes. section 6.27
with open('myfile.txt', 'w') as f:
f.write('abc\n')
f.write('def\n')
A minimal writing example makes the managed block and automatic close behavior concrete. section 6.9





