Python File Handling Basics: Modes, Read/Write Traces and Exam Traps
Learn a mechanical way to solve Python file questions: apply the mode first, track the cursor and newlines, then compute returned values and final contents.
KnowledgeGate Team
Exam prep & CS education

open(), read() and write() look simple on their own, but output questions combine the starting contents, file mode, cursor position, newline characters and open or closed state. Use a mechanical method: write the initial state, apply the mode's first effect, trace each operation, then record the final contents. Together they require tracking the mode, cursor, newline and stream state. The broader File Handling in Python: Read, Write, CSV, Binary Examples tutorial covers general path, CSV and binary handling; this post focuses on Python mode effects, cursor traces and exact output calculations. The Coding & DSA Courses for Placements category provides the broader programming route.
1. Python files and file objects: the mental model
A file is a named sequence of data stored outside the running program. The path identifies that stored resource, while the file object returned by open() tracks its mode, current cursor position and open or closed state. Path("scores.txt") is relative to the process's current working directory. An absolute path starts from a filesystem root.
The context-manager form controls the object's lifetime:
with open("notes.txt", "r", encoding="utf-8") as file:
print(file.closed) # False
print(file.closed) # TrueThe file is closed when the block ends, even if an exception interrupts it. Calling file.read() afterwards raises ValueError: I/O operation on closed file. If strings, lists or functions still feel unfamiliar, follow the Python Tutorial: 13-Step Self-Study Path to DSA before combining them with file operations.
2. Python file modes: predict the first effect before the operation
The mode may change the file before the first statement inside the block runs.
mode | must already exist? | initial effect | main use |
|---|---|---|---|
| Yes | Opens without changing content; otherwise raises | Read existing data |
| No | Creates an absent file or immediately truncates an existing file | Replace content |
| No | Creates an absent file and places writes at the end | Preserve and append |
| No | Creates a new file or raises | Avoid accidental replacement |
t is the default text modifier, b selects bytes, and + allows both reading and writing while retaining the base mode's creation or truncation rule. Starting with exact content old\n, mode w followed by write("new\n") leaves only new\n. Mode a leaves old\nnew\n. Mode r changes nothing, while x fails before any write. The safe habit is simple: write down the mode's immediate effect before tracing the body.
3. Python file handling worked example: write, append, read and total rows
Trace this program one block at a time:
from pathlib import Path
path = Path("scores.txt")
with path.open("w", encoding="utf-8") as file:
first_count = file.write("Asha,72\nRavi,85\n")
with path.open("a", encoding="utf-8") as file:
appended_count = file.write("Meera,91\n")
with path.open("r", encoding="utf-8") as file:
rows = file.readlines()
total = sum(int(row.rstrip("\n").split(",")[1]) for row in rows)
print(first_count, appended_count, total)step | operation and returned value | file state |
|---|---|---|
1 |
|
|
2 |
|
|
3 |
|
|
Removing only each final \n, splitting on the comma and converting field 2 gives 72, 85 and 91. Therefore, 72 + 85 + 91 = 248, and the exact output is 16 9 248.

Each with block creates a separate file-object lifetime. The first writer closes before the append object opens, so its buffered text is available for the append. The reader opens only after the appender closes. For a structured treatment of these ideas, use Python Course: Concepts, MCQs & Coding.
4. read(), readline(), readlines(), tell() and seek(): trace the cursor
Suppose notes.txt contains the exact 15-character text red\nblue\ngreen\n. Run these operations in one r block: first = file.read(4), p1 = file.tell(), second = file.readline(), p2 = file.tell(), file.seek(0), all_lines = file.readlines(), then p3 = file.tell().
operation | returned value | position after |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
read(n) consumes up to n characters in text mode. readline() consumes one line, including its terminating newline when present, while readlines() consumes the remaining lines into a list. At end-of-file, read() and readline() return '', not None. In text mode, tell() returns a position token that can be passed to seek(). Do not treat every text-mode position as a portable byte count.

5. Text mode, binary mode and UTF-8: characters are not always bytes
Text mode reads and writes str. An encoding translates between those characters and stored bytes. Binary mode reads and writes bytes without text decoding.
For text = "café\n", len(text) == 5. After encoded = text.encode("utf-8"), the value is b'caf\xc3\xa9\n', its byte values are [99, 97, 102, 195, 169, 10], and len(encoded) == 6. The difference occurs because é uses two UTF-8 bytes.
The stream type still controls what can be written. A text stream rejects file.write(encoded) with TypeError, and a binary stream rejects file.write(text) with TypeError. In wb mode, file.write(encoded) returns 6; in text mode, file.write(text) reports 5 characters. Use an explicit encoding="utf-8" for predictable text handling, and never assume that a character count is the stored byte size.
6. Python file handling traps that change the answer
Each common trap has a direct correction:
Truncation: Opening an existing file with
wtruncates beforewrite()runs. Even an emptywith open("data.txt", "w"):block leaves an empty file. Useato preserve content, orr+only when you deliberately manage the cursor and overwrite behaviour.Broad stripping: For
line = " Ravi,85\n",line.strip()returns"Ravi,85", removing both leading spaces and the newline.line.rstrip("\n")returns" Ravi,85". Choose the narrower operation when spaces matter.Relative paths: A relative path is resolved from the current working directory, which may not be where the source file sits. Inspect
Path.cwd()or build the path from a known base.Wrong mode or lifetime:
read()on aw-only object raisesio.UnsupportedOperation: not readable. Any I/O after itswithblock raisesValueError. Choose a readable mode and keep required operations inside a valid file-object lifetime.
7. How assessments test Python file basics
Common formats ask you to choose a mode, predict final contents, trace a cursor, identify an exception, distinguish str from bytes, or parse delimited text. KnowledgeGate has about 10 published questions mapped to the File Basics subtopic, but the solving method matters more than memorising patterns.
Try these three timed checks:
Check A:
log.txtstarts asA\n. Opening it withaand callingwrite("B\n")returns2and leavesA\nB\n.Check B:
data.txtstarts as10\n20\n.read(3)returns'10\n', the nextreadline()returns'20\n', and one morereadline()returns''.Check C:
new.txtalready exists. Opening it withxraisesFileExistsErrorbefore the body runs, so no replacement content is written.
These checks test state, cursor and failure timing without relying on any named assessment's pattern. Continue with Python Text Files: Concepts, Worked Examples and Exam Patterns for text-mode records and cursor practice.
8. Python file handling basics: the short version and next step
Use five checks for every file question:
Write the starting contents.
Apply the mode's immediate effect.
Trace the cursor after each operation.
Preserve newline and type information.
Record the returned value and final contents.
The essentials follow from that method: with controls lifetime, w truncates, a appends, reading advances the cursor, and UTF-8 character counts can differ from byte counts. Once file parsing feels routine, DSA Using Python is a useful later progression into broader problem solving.
Keep learning
File Handling in Python: Read, Write, Append, CSV and Binary Examples
Learn a reliable file-handling workflow through one scores file, then apply it to cursor control, append mode, CSV quoting, binary records and common errors.
File Handling in Java: Read, Write, Append and Copy Files Safely
Learn how Java's Path, Files, character streams and byte streams fit together. Build a score file, aggregate its rows, and copy binary data safely.
File Handling in C++: Read, Write, Append and Seek with Examples
Learn how C++ file streams work through connected text and binary examples, from safe record parsing to appending data and updating a fixed record.
File Handling in C: fopen, Read, Write, Append and Seek with Runnable Examples
Build safe C file workflows with text and binary examples. Write records, total them, append data, seek by byte offset, and handle failures.





