Editor

Find a Record in a Binary File

#589 · File handling · Intermediate · 65 XP · about 10 min

A school saves each student as a list [roll, name, marks] in a binary file, with one pickle.dump call per record. To read such a file you call pickle.load again and again: each call gives the next record, and at the end of the file it raises EOFError.

Write find_student(filename, roll) that reads the records one at a time and returns the first one whose roll number is roll. Return 'Not found' if no record has that roll number, and 'No file' if the file does not exist.

Examples

If students.dat holds the records [1, 'Asha', 88], [2, 'Ben', 72] and [3, 'Cara', 65]:

find_student('students.dat', 2)        # returns [2, 'Ben', 72]
find_student('students.dat', 9)        # returns 'Not found'
find_student('missing.dat', 1)         # returns 'No file'

Constraints

  • The file holds at most 10,000 records.
  • Stop reading as soon as you find the record.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.