When a program must preserve data after it stops, it can read strings from a file and write strings back to the filesystem. A file provides persistent storage, while Python programs often parse its contents into lists, dictionaries, sets, CSV records, or JSON data. Files also support familiar interfaces for activities such as reading, writing, and iterating through data. section 5.0
Work with files by choosing an appropriate access and processing pattern:
- Open a file for reading or writing, then iterate over it one line at a time instead of loading the entire contents into memory. section 5.36
- Accumulate related measurements in a dictionary while processing each line; use split to count words and a set to retain unique words. section 5.12
- Use a with block for file operations so files are closed and written data is flushed when the block ends. section 5.32
- Prefer reading from one file and writing to another when transforming content, rather than risking accidental overwrites through simultaneous read/write access. section 5.32
Reverse each line into a new file
A file transformation can read one line at a time, remove its trailing newline, reverse the remaining characters with s[::-1], and write the result plus a newline to a separate output file: with open(input_name) as input_file, open(output_name, 'w') as output_file: for line in input_file: output_file.write(line.rstrip()[::-1] + '\n') For input containing "abc def" and "ghi jkl", the output becomes "fed cba" and "lkj ihg". The separate output preserves the input while producing a transformed copy. section 5.31 section 5.32
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 file operations with related Python tools, including with, context managers, os.stat, os.listdir, glob.glob, CSV, and JSON handling. section 5.0







