A file is a persistent, named storage resource that Python can open, read, write, iterate over, and close. A practical pattern is to process an input file one line at a time instead of loading the whole file into memory. This supports counting, searching, extraction, and transformation tasks. section 6.11 section 6.30
Use this strategy when analyzing or transforming text files:
- Open the file for reading or writing, preferably inside a with statement. section 6.27
- Iterate over the input file one line at a time. section 6.11
- Accumulate related results in suitable data structures, such as a dictionary for counts or a set for unique words. section 6.11
- Write transformed results to a separate output file when possible; reading and writing the same file with r+ can overwrite unintended content. section 6.27
Reverse each input line
A file transformation can preserve line structure while reversing each line's content: read a line, remove its trailing newline with rstrip(), reverse the remaining string with line[::-1], and write the result followed by a newline. Opening both files in one with statement closes them automatically and flushes the output. section 6.26 section 6.27
abc def ghi jkl
Compare the original two-line file with its transformed output to see how line-preserving reversal works. section 6.26







