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:
[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.
{'roll': 1, 'name': 'Ravi', 'marks': 78}Longer, and it says what each part means: record['marks']. Easier to read six months later.
2One dump() for each record
Open the file in 'wb', loop over the records, and call dump() once for each:
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.')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.
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:
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.')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.
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:
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:
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])[[1, 'Ravi', 78], [2, 'Meera', 91], [3, 'Amit', 65]] Ravi scored 78 Meera scored 91 Amit scored 65
- 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 load() gives you everything
- No loop needed to read it
- Appending means loading it all and writing it all back
- Fine for small files
5Recap
One row of your data. Lists are what the papers use; dictionaries say what each part means.
Creates the file, and empties it if it already exists.
The records stack up in the file, one behind the other, in the order they were written.
int(input(...)) before the record is built, so the numbers come back as numbers.
Until then, what you dumped may still be in the buffer.
Then one load() returns everything. Simpler to read, harder to add to.
- 1
Create
book.datwith five books, each a list of book number, title and price.Hint · float(input(...)) for the price.
- 2
Run your create program twice and count the records.
Hint · Still five. 'wb' emptied the file first.
- 3
Write the same file using dictionaries instead of lists as the records.
Hint · {'bno': 1, 'title': 'Python', 'price': 250.0}
- 4
Write a program that saves the whole list of records with a single
dump(), and read it back with oneload().Hint · No loop on the way out, and no loop on the way in.
A program dumps three records and is run twice, opening the file in 'wb' each time. How many records are in the file?
Why is int() used on the marks before dump() rather than after load()?
What is in the file after pickle.dump(students, f), where students is a list of three records?