๐Ÿ”ฅ 75% OFF Early-bird โ‚น2,999 one time โณ BOARDS ARE CLOSE Lock this price before it goes up. Grab my seat โ†’
Subjects โ€บ Computer Science โ€บ File Handling

File Handling

Big scorer โ‰ˆ 13.6 marks in a typical paper ยท Medium effort ยท 49 questions shown
๐Ÿ“Œ How to approach this chapter

In a typical paper this chapter carries about 13.6 marks. Fixed patterns: read lines/words, binary record search/update, CSV read/write.

  • What the questions look like: 3-mark "write a function that reads a text file and counts/displays lines, words or vowels", 4-mark CSV or binary-file task, 5-mark binary file with search/update, and 1-mark MCQs on file modes.
  • Text modes: "r" read (file must exist), "w" write (erases old content), "a" append, "r+" read and write without erasing, "w+", "a+". Binary: add b (rb, wb, ab, rb+). Always use with open(...) as f: so the file closes itself.
  • read() whole file as string, readline() one line, readlines() list of lines (each ends with \n). Iterating "for line in f" is the simplest way to read line by line. split() breaks a line into words.
  • Binary files: import pickle; pickle.dump(record, f) writes; pickle.load(f) reads one record and raises EOFError at the end - loop with try/except EOFError. To update a record: f.seek(position) then dump again, using f.tell() to remember the position before each load.
  • CSV: import csv; csv.reader(f) gives each row as a list; csv.writer(f).writerow([...]) / writerows(list); open with newline="" when writing. Use the first column as key when searching.
  • Pattern for most programs: open file -> loop -> test condition -> print/count -> close. Write this skeleton first, then fill in the condition.
You can try the first few questions here. Start free for 5 days to open everything.