LambdaLabTM
Computer Science · Class 12 · Binary Files
Binary filesWriting⏱️ 14 min read

Creating a Binary File

A binary file of records is what every board question is about, and making one is a loop with a dump() in it. The decision worth understanding first is what one record should be.

1What a record is

A record is one row of your data — one student, one book, one item. In Python it is usually a list or a dictionary, and either is correct:

As a list
[1, 'Ravi', 78]

Short to write. You reach the parts by position — record[0] is the roll number, record[2] the marks. This is what most board answers use.

As a dictionary
{'roll': 1, 'name': 'Ravi', 'marks': 78}

Longer, and it says what each part means: record['marks']. Easier to read six months later.

Note
This chapter uses the list form, because that is the form the question papers use. Everything works exactly the same with dictionaries — only the way you reach the parts changes.

2One dump() for each record

Open the file in 'wb', loop over the records, and call dump() once for each:

create_file.py
import pickle

students = [
    [1, 'Ravi', 78],
    [2, 'Meera', 91],
    [3, 'Amit', 65],
]

f = open('student.dat', 'wb')
for s in students:
    pickle.dump(s, f)
f.close()

print('File created with', len(students), 'records.')
Output
File created with 3 records.
open('student.dat', 'wb')

Write, binary. The file is created if it is not there — and emptied if it is.

for s in students:

s is one record: a list of three values.

pickle.dump(s, f)

One record written. The next dump() carries straight on after it, so the records end up stacked one behind the other.

f.close()

Not optional. Until this runs, the records may still be sitting in the buffer.

'wb' empties the file first
Run this program twice and you still have three records, not six. Every open('student.dat', 'wb') starts the file again from nothing. Adding to a file that already has records is 'ab', and it has its own lesson.

3Records typed in by the user

The board usually asks for the records to be entered rather than written into the program. Same loop, with input() filling the record:

create_typed.py
import pickle

f = open('student.dat', 'wb')
more = 'y'

while more == 'y':
    roll = int(input('Roll number : '))
    name = input('Name        : ')
    marks = int(input('Marks       : '))

    pickle.dump([roll, name, marks], f)
    more = input('One more (y/n)? ')

f.close()
print('File created.')
Output
Roll number : 1
Name        : Ravi
Marks       : 78
One more (y/n)? y
Roll number : 2
Name        : Meera
Marks       : 91
One more (y/n)? n
File created.
int() on the way in, not on the way out
input() always gives a string, so the roll number and the marks are converted before they go into the record. Do that and they come back as numbers for ever after — which is the whole advantage a binary file has over a text one.

Try it here. Type your own records, then read them back:

create_typed.py

4Or one dump() for the whole list

dump() can take the entire list of records in one call. Then the file holds one object — a list — and one load() brings all of it back:

one_dump.py
import pickle

students = [[1, 'Ravi', 78], [2, 'Meera', 91], [3, 'Amit', 65]]

f = open('all.dat', 'wb')
pickle.dump(students, f)
f.close()

f = open('all.dat', 'rb')
back = pickle.load(f)
f.close()

print(back)
for s in back:
    print(s[1], 'scored', s[2])
Output
[[1, 'Ravi', 78], [2, 'Meera', 91], [3, 'Amit', 65]]
Ravi scored 78
Meera scored 91
Amit scored 65
One dump per record
  • Records can be appended later with 'ab'
  • Read one at a time — a huge file still fits in memory
  • Needs the EOFError loop to read them all
  • What board answers use
One dump for the whole list
  • One load() gives you everything
  • No loop needed to read it
  • Appending means loading it all and writing it all back
  • Fine for small files
Key Takeaway
Both are correct. This chapter uses one dump per record from here on, because that is the form the search, append and update lessons are all about — and the form a board question expects.

5Recap

A record is a list or a dictionary

One row of your data. Lists are what the papers use; dictionaries say what each part means.

Open in 'wb'

Creates the file, and empties it if it already exists.

One dump() per record

The records stack up in the file, one behind the other, in the order they were written.

Convert on the way in

int(input(...)) before the record is built, so the numbers come back as numbers.

close() when the loop ends

Until then, what you dumped may still be in the buffer.

Or dump the whole list at once

Then one load() returns everything. Simpler to read, harder to add to.

✍️ Now write these yourself
  1. 1

    Create book.dat with five books, each a list of book number, title and price.

    Hint · float(input(...)) for the price.

  2. 2

    Run your create program twice and count the records.

    Hint · Still five. 'wb' emptied the file first.

  3. 3

    Write the same file using dictionaries instead of lists as the records.

    Hint · {'bno': 1, 'title': 'Python', 'price': 250.0}

  4. 4

    Write a program that saves the whole list of records with a single dump(), and read it back with one load().

    Hint · No loop on the way out, and no loop on the way in.

Quick Check

A program dumps three records and is run twice, opening the file in 'wb' each time. How many records are in the file?

Quick Check

Why is int() used on the marks before dump() rather than after load()?

Quick Check

What is in the file after pickle.dump(students, f), where students is a list of three records?