1. Files, kinds of file and paths
A file keeps data on disk after a program ends (data in variables are lost).
- Text file: characters in lines; each line ends with the EOL character
\n. Readable in any editor. - Binary file: raw bytes, e.g. Python objects stored with pickle; not human-readable.
- CSV file: a text file of comma-separated values, one record per line; opens in spreadsheets.
Paths. An absolute path starts at the root (C:\School\cs\a.txt, /home/asha/cs/a.txt). A relative path starts at the current working directory (a.txt, data\a.txt, ..\a.txt, where .. is the parent folder).
| Kind | What it stores | Typical use | Read with |
|---|---|---|---|
| Text | Characters in lines ending with \n | Notices, logs, stories | read(), readline(), readlines() |
| Binary | Raw bytes, e.g. pickled Python objects | Records kept as lists or dictionaries | pickle.load() |
| CSV | Text lines of comma-separated values | Tables shared with spreadsheets | csv.reader() |
| Path | Kind | Meaning |
|---|---|---|
C:\School\CS\notes.txt | Absolute (Windows) | Full location from the drive root |
/home/asha/cs/notes.txt | Absolute (Linux) | Full location from the root / |
notes.txt | Relative | In the current working directory |
data\notes.txt | Relative | In the data folder inside the current one |
..\notes.txt | Relative | In the parent of the current folder |
Key terms
- EOL
End-of-line character (\n) that ends each line of a text file.
- Absolute path
The full location of a file from the root of the drive.
- Relative path
A location worked out from the current working directory.
2. Opening and closing files
f = open(name, mode) returns a file object; f.close() saves and releases the file.
"r"read (default; file must exist),"w"write (creates or empties),"a"append (creates or adds at the end)."r+","w+","a+"add the other operation; addbfor binary:"rb","wb","ab".
The with statement closes the file automatically, even after an error:
with open("notes.txt", "a") as f:
f.write("New entry\n")
| Mode | Opens for | If the file exists | If it does not exist | Pointer starts at |
|---|---|---|---|---|
r | Reading (default) | Read from the start | FileNotFoundError | Beginning |
w | Writing | Emptied (truncated) | Created | Beginning |
a | Appending | Kept; writes go at the end | Created | End |
r+ | Reading and writing | Kept | FileNotFoundError | Beginning |
w+ | Writing and reading | Emptied | Created | Beginning |
a+ | Appending and reading | Kept | Created | End |
rb wb ab … | The same, in binary | As above | As above | As above |
Key terms
- File object
The object returned by open(), through which a program reads or writes.
- Context manager
The with statement, which closes the file when its block ends.
3. Reading and writing text files
Writing: write(s) writes one string and returns its length; writelines(list) writes each string. Neither adds \n. Convert numbers with str().
Reading: read() → whole remaining text as one string; read(n) → n characters; readline() → one line ("" at the end of the file); readlines() → list of lines; for line in f: → one line per pass.
Output of the writing example (run in Python):
Line one
Line two
Line three
| Call on a freshly opened hills.txt | Returns (run in Python) |
|---|---|
f.read() | 'Clouds gather over the hills\nthe bus waits at the stop\ntea stalls o |
f.read(6) | 'Clouds' |
f.readline() | 'Clouds gather over the hills\n' |
f.readlines()[1] | 'the bus waits at the stop\n' |
| Statement | Effect |
|---|---|
n = f.write("Line one\n") | writes one string and returns its length: n is 9 |
f.writelines(["Line two\n", "Line three\n"]) | writes each string of the list, adding nothing between them |
| File afterwards | Line one, Line two, Line three |
4. seek(), tell() and processing lines
tell() gives the file pointer's position in bytes; seek(n) moves it to byte n (seek(0) = start).
Typical processing tasks: count lines, words (split()), characters (len()), or lines that start with a letter; display long words; copy selected lines to another file opened in "w" mode.
with open("routes.txt") as src, open("caps.txt", "w") as dst:
for line in src:
if line[0].isupper():
dst.write(line)
Resulting caps.txt (run in Python):
Route 7 Kothrud
Route 3 Hadapsar
Route 21 Wakad
| Step on stock.txt | tell() before | Returned |
|---|---|---|
readline() | 0 | 'pens 40\n' |
read(7) | 8 | 'erasers' |
seek(0), then read(4) | 0 | 'pens' |
| Line | Words in line | Characters (with \n) | Words so far | Characters so far |
|---|---|---|---|---|
| 1 | 5 | 29 | 5 | 29 |
| 2 | 6 | 26 | 11 | 55 |
| 3 | 6 | 27 | 17 | 82 |
| 4 | 4 | 23 | 21 | 105 |
5. Binary files with pickle
import pickle. Pickling (pickle.dump(obj, f)) writes an object as bytes; unpickling (pickle.load(f)) reads the next object back.
- Open in
"wb"(new file),"ab"(add records) or"rb"(read). - Read till the end: call
load()inwhile Trueinsidetry, and stop onexcept EOFError. - Search: load each record and test it; use a flag to report "not found".
- Update: load all records into a list, change in memory, dump all again in
"wb".
Appending a fifth record and counting again (run in Python):
import pickle
with open("books.dat", "ab") as f:
pickle.dump([105, "Blue Kettle", 210], f)
n = 0
with open("books.dat", "rb") as f:
try:
while True:
pickle.load(f)
n += 1
except EOFError:
pass
print(n)
Output: 5
Key terms
- Pickling
Converting a Python object into a byte stream (serialisation) with dump().
- Unpickling
Rebuilding the object from the byte stream (deserialisation) with load().
- EOFError
Raised by load() when no object is left in the file.
6. CSV files
import csv. Open with newline="" so that the writer controls line endings.
- Writing:
w = csv.writer(f), thenw.writerow(list)orw.writerows(list_of_lists). - Reading:
for row in csv.reader(f):gives each line as a list of strings;next(reader)skips the header; convert numbers withint().
import csv
with open("marks.csv", newline="") as f:
for row in csv.reader(f):
print(row)
Output (run in Python):
['roll', 'name', 'marks']
['1', 'Aarav', '78']
['2', 'Bina', '91']
['3', 'Chetan', '64']
['4', 'Divya', '85']
| Step | Code |
|---|---|
| Import the module | import csv |
Open with newline="" | f = open("marks.csv", "w", newline="") |
| Create a writer | w = csv.writer(f) |
| Write one row | w.writerow(["roll", "name", "marks"]) |
| Write many rows | w.writerows([[1, "Aarav", 78], [2, "Bina", 91]]) |
| Close | f.close() (or use with) |
| Feature | Text | Binary (pickle) | CSV |
|---|---|---|---|
| Stores | characters in lines | bytes of Python objects | comma-separated text |
| Human-readable? | Yes | No | Yes |
| Write with | write(), writelines() | pickle.dump() | writerow(), writerows() |
| Read with | read(), readline(), readlines() | pickle.load() until EOFError | csv.reader() |
| Types after reading | str | the original types | str in every field |
Key terms
- CSV
Comma-separated values: a text file holding a table, one record per line.
- Delimiter
The character that separates fields (a comma by default).
Exam tips
Common mistakes
- Opening an existing file in
"w"when the task says add: the old data are lost. - Forgetting
\ninwrite(), or comparing a line withoutstrip(). - Writing numbers without
str()(TypeError). - Using text modes with pickle, or forgetting
import pickle. - Reading a binary file with a fixed loop count instead of handling EOFError.
- Adding CSV fields without
int(), or forgetting to skip the header.
How marks are usually awarded
- Output questions: each correct line of output.
- Functions on files: importing the module, opening in the right mode, the loop, the condition or logic, and the result.
- Error-finding: 1 mark per error identified and corrected.