Skip to the solution
EasyBackend14 min read

How do you read and write files in Python?

564 views

The problem

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 are r, w (truncates), a (appends), x (create only, fails if it exists), plus b for binary and + for read/write
  • with 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 str using an encoding and translates newlines; binary mode gives raw bytes. Always pass encoding="utf-8" because the default depends on the locale (PEP 686 makes UTF-8 the default only from Python 3.15)
  • read() loads everything; iterating for line in f streams one line at a time with flat memory; readlines() builds a list
  • pathlib.Path gives read_text, write_text, read_bytes, write_bytes, mkdir(parents=True) and / path joining
  • Safe overwrites: write to a temp file, then os.replace it 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.

  • files
  • pathlib
  • io

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

14 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonModes, with blocks, reading line by line, and the two common errors
Pythonpathlib, binary mode, newlines, encodings and an atomic replace

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 19 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

What is the difference between a list and a tuple?

Continue