AmbifulWorksheets
Cheat sheet
CBSE · Class 12 · Computer Science

File Handling in Python

Text files with open() modes, read, readline, readlines, write, seek and tell; binary files with pickle; and CSV files with reader and writer.

Key ideas

Remember

Text modes'r' read; 'w' write, emptying it; 'a' append; 'r+' read and write, file must exist
More modes'w+' write and read, emptying it; 'a+' append and read; 'rb', 'wb', 'ab' for binary files
A file of two lines, ab and cdread() = 'ab\ncd\n' (6 characters); readline() = 'ab\n'; readlines() = ['ab\n', 'cd\n']
seek and tellafter read(4), tell() gives 4; seek(0) goes back to the start
Reading every recordcall pickle.load(f) in a while True loop inside try; except EOFError ends it
CSVopen with newline=''; next(r) skips the header row; int(row[2]) turns text into a number

Watch out

Worked example

What lines does class.csv hold after this runs? (a) How many lines? (b) Write the last line.
import csv
f = open('class.csv', 'w', newline='')
w = csv.writer(f)
w.writerow(['name', 'class', 'marks'])
w.writerows([['Arjun', 12, 49], ['Rohan', 12, 98], ['Kabir', 11, 45]])
f.close()

Working: writerows() writes one line per inner list, fields separated by commas: name,class,marks / Arjun,12,49 / Rohan,12,98 / Kabir,11,45

Answer: (a) 4; (b) Kabir,11,45