Interview Q&A / Python
Python interview questions
Lists, dictionaries, generators, decorators and the Python questions asked in service-company and data roles.
Prefer rapid revision? Practise Python short interview answers →
- How do you read and write JSON in Python?
Use the json module: json.dumps and json.loads convert between Python objects and JSON strings, while json.dump and json.load do the same with file objects. JSON null becomes None, and keys always become strings.
BeginnerQuick answer1 min read - What are the common file modes in Python's open() function?
r" reads (default), "w" writes and erases existing content, "a" appends to the end, and "x" creates a new file and fails if it exists. Adding "+" allows both read and write, and "b" means binary instead of text.
BeginnerQuick answer1 min read - Why do we use the with statement when working with files?
with guarantees the file is closed when the block ends, even if an exception occurs. It works through a context manager, an object with __enter__ and __exit__ methods, so cleanup does not depend on remembering to call close().
BeginnerQuick answer1 min read - How do you read a very large file in Python without loading it all into memory?
Iterate over the file object directly with for line in f. It reads one line at a time through a buffer, so memory use stays small. read() and readlines() load everything at once and can exhaust memory on big files.
IntermediateQuick answer1 min read - What is pathlib, and why is it preferred over os.path?
pathlib represents file paths as objects, so you can join them with /, read their parts and read or write files through methods. It is more readable than string-based os.path calls and handles Windows and Linux separators for you.
IntermediateQuick answer1 min read