Python / Core Python Fundamentals Interview Questions
How do you read from and write to files in Python?
Python's built-in open() function returns a file object. Always use it as a context manager with with — this guarantees the file is closed (and the OS buffer flushed) even if an exception occurs, avoiding resource leaks.
# Writing a file with open('notes.txt', 'w', encoding='utf-8') as f: f.write('Line one\n') f.writelines(['Line two\n', 'Line three\n']) # Reading the whole file at once with open('notes.txt', encoding='utf-8') as f: content = f.read() # one big string # Reading line by line (memory-efficient for large files) with open('notes.txt', encoding='utf-8') as f: for line in f: # file object is itself an iterator print(line.rstrip()) # strip trailing newline # Reading all lines into a list with open('notes.txt', encoding='utf-8') as f: lines = f.readlines() # ['Line one\n', 'Line two\n', ...]
Mode strings: 'r' (read, default), 'w' (write, truncates), 'a' (append), 'x' (exclusive create, fails if exists), 'b' suffix for binary mode ('rb', 'wb'). Always specify encoding='utf-8' explicitly — relying on the platform default causes bugs on Windows where the default is often cp1252.
For JSON specifically, import json and use json.load(f) / json.dump(data, f, indent=2) inside a with open() block. For CSV, the csv.DictReader and csv.DictWriter classes handle quoting and delimiter edge cases correctly.
More Related questions...