File Handling
Reading Files
read, readline, readlines, and iteration methods
Interview: File input — tests understanding of memory-efficient reading and different reading strategies
Python provides multiple ways to read file content. The right method depends on file size and what you need to do with the data. For large files, iterate line by line; for small files, read all at once.
Reading Methods
f.read(): Read entire file as one stringf.read(n): Read n characters/bytesf.readline(): Read one line at a timef.readlines(): Read all lines into a listfor line in f: Iterate lines (most memory-efficient)
Interview Tip
Know when to use each method. for line in f is the most Pythonic for line-by-line processing and uses minimal memory regardless of file size.
Use Cases
Processing log files line by line (memory efficient)
Reading configuration files at startup
Parsing CSV/JSON data files
Reading large files in chunks (binary data, media files)
Implementing file-based search (grep-like functionality)
Common Mistakes
Using readlines() on large files — loads everything into memory
Forgetting to strip newlines: line.strip() or line.rstrip()
Not handling encoding errors with errors= parameter
Using read() when readline() would suffice (reads entire file)
Forgetting that after read(), the file pointer is at the end (need seek(0))