Explore reading and writing text files, choosing file modes, using context managers and handling structured data safely.
01
Learning objectives
Explain why programs persist data in files rather than keeping everything in memory.
Read and write text files using open and context managers.
Distinguish read, write and append modes and describe their effects.
Handle file paths, encoding and malformed input deliberately.
02
Lesson notes
A variable normally exists only while the program is running. A file stores information beyond one execution, allowing a program to reload user settings, reports or records later. A file has a path, a format and permissions. Text files contain characters; binary files contain bytes and require an appropriate format or decoder.
Python opens files with open(path, mode, encoding). Read mode r expects an existing file, write mode w creates or truncates a file, and append mode a adds to the end. Choose the mode deliberately: opening an important file in w can destroy its previous contents. UTF-8 is a common text encoding and should be specified when portability matters.
A context manager is the safest normal pattern: with open(...) as file: ... . The with statement guarantees that the file is closed when the block exits, including when an exception occurs. read() loads content, readline() reads one line, and iteration over a file processes it line by line without loading the entire file into memory.
Robust file processing validates input and handles expected failures such as FileNotFoundError, PermissionError and UnicodeDecodeError. Keep file data separate from trusted program logic; never assume a CSV field is numeric just because it usually contains a number. For larger structured data, use a suitable parser rather than splitting complex formats by hand.
03
Worked code examples
Worked example
Path offers a readable cross-platform interface for common file operations. The example creates a temporary file, reads it, then removes it.