Worksheets › Class 12 › File Handling in Python › Cheat sheet

Class 12 File Handling in Python: cheat sheet

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

Open the printable cheat sheetPractice worksheet

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

Practise File Handling in Python

Revise with this page, then practise: every File Handling in Python sheet in the app is new, with an answer key and working.

Coming soon for Android and iPhone.