Question presented to candidate: "Walk me through how you read and write files in Python. Which modes would you use, how do you make sure the file gets closed, and what goes wrong with encodings and large files?"
What a strong answer should cover:
open(path, mode, encoding=...)returns a file object; the common modes arer,w(truncates),a(appends),x(create only, fails if it exists), plusbfor binary and+for read/writewith open(...) as f:closes the file even when an exception is raised, because the file object is a context manager- Text mode decodes bytes to
strusing an encoding and translates newlines; binary mode gives rawbytes. Always passencoding="utf-8"because the default depends on the locale (PEP 686 makes UTF-8 the default only from Python 3.15) read()loads everything; iteratingfor line in fstreams one line at a time with flat memory;readlines()builds a listpathlib.Pathgivesread_text,write_text,read_bytes,write_bytes,mkdir(parents=True)and/path joining- Safe overwrites: write to a temp file, then
os.replaceit over the target
Clarifying questions expected:
- Is the data text or binary, and if text, which encoding does it use?
- How large can the file get: does it fit in memory?
Code / implementation expected: Yes β a short with open(...) read/write, ideally showing streaming and an explicit encoding.