Lesson · File I/O & Filesystem
File Basics
58 min readFile Basics
File objects are streams with text or binary modes, buffering, and a lifetime that must be managed. Correct mode selection and cleanup are the foundation of reliable file I/O.
Learning goals
- Open a file with
path.open()and choose the mode ("r","w","a","x") that matches whether you intend to read, create, replace, or extend it. - Explain what
withguarantees about closing and flushing, including when the block body raises an exception. - Describe how text mode turns bytes into
strthrough an encoding, and which exception a failed decode raises. - Predict the difference between writing to an existing path in
"w"mode and in"a"mode. - Say when written data becomes visible to another process and how buffering affects that moment.
Mental model
Read the diagram as the lifetime of one file object: creation, use, release. The mode is a promise about what the code will do to the file, and text versus binary decides whether the stream carries str or bytes. Bugs usually come from losing track of the last step, where the buffer is flushed and the handle is closed.
Mental model
read it top to bottom
open(path, mode, encoding) ↓ mode fixes the legal operations: read / overwrite / append / create file object (a stream of str or bytes) ↓ read() and write() move data through it with block ends → flush and close release the file
Core idea
Every file operation is an agreement with the outside world: the mode declares what you will do before any data moves, and with guarantees the hand-back step, closing and flushing the file even when the body raises. Choose the narrowest mode for the job and be explicit about encoding, because those two decisions fix which operations are legal and how bytes become text.
open()
open() returns a file object configured for a path, mode, encoding, buffering policy, and related options. Text mode returns strings, while binary mode returns bytes.
Modes
A mode is a short string passed to open() that selects the legal operations for the life of the file object: "r" reads, "w" truncates or creates before writing, "a" writes at the end of the file (creating it if needed), and "x" creates only when the path does not exist. Adding "b" switches the stream to bytes, and using a method the mode forbids, such as write on "r", raises io.UnsupportedOperation.
Text mode
Text mode is the default family: data crosses the stream as str, newlines are translated to \n when reading and to the platform separator when writing, and bytes are decoded with encoding= or, when it is omitted, the platform locale encoding. A byte sequence that is invalid in the chosen encoding raises UnicodeDecodeError on read and UnicodeEncodeError on write.
Binary mode
Binary mode reads and writes bytes without text encoding or newline translation. Use it for images, compressed data, executable formats, and protocols defined in bytes.
Reading
Reading pulls data from the stream: read() with no argument returns the rest of the file as one str, read(size) returns at most that many characters, readline() returns one line including its \n, and iterating yields lines in order. At end of file these all return '', and each call advances the position, so a partial read resumes where the previous one stopped.
Writing
Writing sends data of the stream's expected type (str in text mode, bytes in binary mode) and returns the number of characters or bytes written; passing the wrong type raises TypeError. Written data can sit in the buffer until flush() or close() runs, so code that must be visible promptly to another process should flush explicitly.
Appending
Appending is "a" mode: every write goes to the end of the existing content, and the file is created if it is missing, so repeated runs add lines instead of replacing them. Unlike "w", opening in append mode never truncates, and "a+" makes reading legal as well.
Buffering basics
Buffering batches I/O operations to reduce system-call overhead. It can affect visibility and latency, so flushing and closing matter when another process or device must see data promptly.
Walkthrough
Path("notes.txt")only points at a location; the file on disk appears when the first block opens it in"w"mode, which creates the file or truncates it if it already exists.file.write("line 1\nline 2\n")sends both lines in one call as astr; the explicit\ncharacters are written as line breaks.- The second block reopens the same path in
"r"mode, andfile.read()returns the whole file as a single string, soprintleaves a trailing blank line because the content already ends with\n. Bothwithstatements close their file when the block ends, flushing the buffer even if the body raises. - Predict before running: the exact output of
print(file.read()), then how a second run of the script changes the file if the first mode is switched from"w"to"a".
Experiments to try
- Run the example, then switch the write mode from
"w"to"a"and run it again. Compare the file contents and explain the difference with the truncation rule of each mode. - Call
writetwice inside the first block and print its return value each time; check the numbers againstlen("line 1\nline 2\n"). - Open the file in
"r"mode and callfile.write("x"); read theio.UnsupportedOperationerror and note that the mode fixed the legal operation set at open time. - Open a path that does not exist in
"r"mode and read theFileNotFoundError, then open an existing path in"x"mode and read theFileExistsError.
Common mistakes
- Using
"w"when the task is appending:"w"truncates the file the moment it opens, so a logging loop silently destroys every previous line before writing its own. - Omitting
encoding="utf-8"in text mode: the stream falls back to the platform locale encoding, so the same code reads or writes different bytes on different machines. - Passing the wrong type to
write: text streams acceptstrand binary streams acceptbytes, so mixing them raisesTypeErrorbecause the mode fixed the expected type at open time. - Reading a file whose writer has not flushed:
writestages characters in a buffer, so a second process can see stale or partial content untilflush()orclose()runs.
Practice: Easy
- Write
greeting.txtwithPath("greeting.txt").write_text("hello\n", encoding="utf-8"), then open it in"r"mode and printfile.read(). State the output before running. - Rewrite the worked example so the write block runs twice into the same file in
"a"mode, and predict how many lines the file holds afterward. - Open a missing path in
"r"mode and record the exact exception; then open the same path in"w"mode and describe what exists on disk afterward.
Practice: Medium
- Extend the example to write with
file.writelines(["a\n", "b\n"])instead ofwrite, then read the file back with tworeadline()calls and compare what each returns, including the\nsuffix. - Demonstrate buffer visibility: write a line in a
"w"block and try to read the file before the block ends, then addfile.flush()and read again. Record what changed and why. - Refactor a broken function that opens
"r"and then writes: catch theio.UnsupportedOperation, split the function into a reader and an appender, and confirm both work.
Practice: Hard
- Build a small append-only logger:
log(path, message)opens the file in"a"mode with UTF-8 and writes one line; define its behavior for an unwritable path and test it across two consecutive runs. - Design a round-trip check for the three modes: create with
"w", extend with"a", read with"r", and assert the final content equals the two expected lines. Explain which mode each assertion protects. - Write the word
caféwithencoding="utf-8", read the file back withencoding="ascii", and explain theUnicodeDecodeErrorwith the decode step text mode performs.
Lesson checklist
- I can name the operation set of each common mode and pick the narrowest one for a task.
- I can explain what
withguarantees when the block body raises. - I can describe how a text-mode read turns bytes into
strand which exception a bad decode raises. - I can say when written data becomes visible to another process.
Remember
A file object is the single tool behind every disk read and write: its mode fixes which operations are legal before data moves, and its text or binary flavor fixes whether that data is `str` or `bytes`. Manage its lifetime with `with`, choose the mode deliberately, and pass `encoding="utf-8"` whenever you work in text mode.
Interview angles
What is the main purpose of **open()**?+
open() returns a file object configured for a path, mode, encoding, buffering policy, and related options. Text mode returns strings, while binary mode returns bytes.
What should you pay attention to when using **Modes**?+
The mode fixes what is legal for the whole life of the file object: "r" reads, "w" truncates then writes, "a" appends past existing content, and "x" refuses to open an existing path. Calling a method the mode forbids raises io.UnsupportedOperation.
How does **Text mode** fit into this lesson?+
Text mode is the default flavor of a file object: str crosses the stream, newlines are translated, and bytes are decoded with encoding= (or the platform locale when it is omitted). A sequence the encoding cannot decode raises UnicodeDecodeError, which is why the worked example passes encoding="utf-8" explicitly.
What does mode `"w"` do to a file that already contains data?+
"w" truncates the file at open time, before the first write, so a loop that reopens with "w" each run silently destroys everything written earlier. Use "a" to add to existing content.