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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
