Need to process a file without loading it all into memory? open() creates and returns a file-like object for the named file. With the default read mode, iterate over that object to receive one line at a time, including each line's newline character. The returned object may be a TextIOWrapper or BufferedReader, while exposing a common file API and allowing buffering optimizations. section 5.2 section 5.36
Choose the mode and usage pattern that match the task:
- Use open(filename) or open(filename, 'r') to read text; r is the default. section 5.2
- Use w to write, a to append, and b with a mode such as rb, wb, or ab for byte-oriented access. section 5.2
- Iterate directly over open(filename) when one pass is enough; use with open(...) to ensure opened files are flushed and closed. section 5.2 section 5.36
- For binary data, read bounded chunks such as 1000 bytes and stop when an empty chunk is returned. section 5.2
Read a file line by line
with open(filename) as f:\n for one_line in f:\n print(len(one_line))\n\nFor CSV output, combine open() with csv.writer:\n\nwith open('/tmp/stuff.csv', 'w') as f:\n o = csv.writer(f)\n o.writerow(range(5))\n o.writerow(['a', 'b', 'c', 'd', 'e']) section 5.2 section 5.21
with open(filename) as f:
for one_line in f:
print(len(one_line))
Compare the compact with-and-iteration pattern with explicit file-object handling. section 5.2








