Notes · Class 12 · CBSE · Science Computer Science
File Handling in Python notes
Revision notes for the chapter: the key points, definitions and exam tips to remember.
Files store data permanently. Python works with text and binary files.
TYPES
- Text files: human-readable characters (.txt, .csv); end-of-line characters.
- Binary files: raw bytes (images, pickled objects).
OPENING AND CLOSING
- f = open("file.txt", mode). Close with f.close().
- with open("file.txt") as f: — closes automatically.
- Modes: "r" (read), "w" (write; overwrites), "a" (append), "r+", "w+", "a+"; add "b" for binary.
READING
- read() (whole file or n characters), readline() (one line), readlines() (list of lines).
- Iterate: for line in f.
WRITING
- write(string), writelines(list of strings).
FILE POINTER
- tell() returns position; seek(offset, from) moves it.
PICKLE (binary files)
- import pickle; pickle.dump(obj, file) to write; pickle.load(file) to read.
CSV FILES
- import csv; csv.writer(f).writerow(row) / writerows(); csv.reader(f) to read.
Memory hook: "w wipes, a adds, r reads."
File Handling in Python: practice questionsFile Handling in Python cheat sheet
More Class 12 · CBSE · Science Computer Science notes
Practise File Handling in Python
Sign up free to practise the full chapter after revising. Questions you get wrong come back until you've mastered them.
Start practising freeFree to start · No credit card needed