0% found this document useful (0 votes)
21 views

Data File Handling - Binary File

Uploaded by

ripultron0007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Data File Handling - Binary File

Uploaded by

ripultron0007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

About Us Website: https://www.learnpython4cbse.

com/ Feedback
eedback 8076665624

Learnpython4cbse Youtube Channel:


Inspiring Success SuperNova-learnpython
learnpython
PYTHON ONLINE CLASSES COMPUTER SC. INFORMATICS PRAC. SAMPLE PAPERS PYTHON MCQs

Data File Handling – Binary File

SuperNova-LearnPython,, a YouTube channel dedicated to helping students to learn Python


and computer science concepts.
The channel covers various topics related to computer science, including Python
networking, SQL and many more.
programming, data file handling, computer networking
If you’re looking for video descriptions, notes, assignments, and previous years’ question
papers related
ed to Python and computer science for class 11 and 12, I recommend checking
out the SuperNova-LearnPython
LearnPython channel on YouTube.
You can find the channel here1.
Happy learning! .
Please like, Subscribe and share the Channel

Page 1 of 16 Website: https://www.learnpython4cbse.com/


About Us Website: https://www.learnpython4cbse.com/ Feedback
eedback 8076665624

Learnpython4cbse Youtube Channel:


Inspiring Success SuperNova-learnpython
learnpython
PYTHON ONLINE CLASSES COMPUTER SC. INFORMATICS PRAC. SAMPLE PAPERS PYTHON MCQs

In this Tutorial, we will discuss about...

Binary file: basic operations on a binary file: open using file open modes (rb, rb+,
wb, wb+, ab, ab+), close a binary file, import pickle module, dump() and load()
method, read, write/create, search, append and update operations in a binary file

What is Binary file?

• In this type of file, there is no terminator for a line and the data is stored after converting
it into machine understandable binary language.
• Operations on binary files are faster as no translation required.
• Example:
– Document files: .pdf, .do.doc, .xls etc.
– Image files: .png, .jpg, .gif, .bmp etc.
– Video files: .mp4, .3gp, .mkv, .avi etc.
– Audio files: .mp3, .wav, .mka, .aac etc.
– Database files: .mdb, .accde, .frm, .sqlite etc.
– Archive files: .zip, .rar, .iso, .7z etc.
– Executable files: .exe, .dll
.dll, .class etc.

Python: pickle module: - Reading and Writing from / into Binary File

• Sometimes we need to write and read structure objects such as dictionary, list and the
objects/instance of a class on a file.
• Python has a module which does this work for us and is extremely easy to use. This module
is called pickle.
• It provides us with the ability to serialize (by using dump () method). Serialization process
is also known as pickling and deserialize (by using load () method) objects, i.e., to convert
objects into bitstreams which can be stored into files and later be used to reconstruct
r the
original objects, it is also known as unpickling.

Page 2 of 16 Website: https://www.learnpython4cbse.com/


About Us Website: https://www.learnpython4cbse.com/ Feedback
eedback 8076665624

Learnpython4cbse Youtube Channel:


Inspiring Success SuperNova-learnpython
learnpython
PYTHON ONLINE CLASSES COMPUTER SC. INFORMATICS PRAC. SAMPLE PAPERS PYTHON MCQs

• There are some data types which pickle cannot serialize, but it is still capable of serializing
most of the objects typically
ically used in Python programs. A comprehensive list of data types
which pickle can serialize.
– None, True, and False
– integers, floating point numbers, complex numbers
– strings, bytes, bytearrays
– tuples, lists, sets, and dictionaries containing only picklable objects
– functions defined at the top level of a module (using def, not lambda)
lambda
– built-in
in functions defined at the top level of a module
– classes that are defined at the top level of a module
In order to work with pickle module, you must import pickle in your program.

• Some of the most common access modes are listed below:

Binary File
Use Description
Mode
This is the default mode. It Opens file for reading. File
‘rb’ Read only
must exists, otherwise Python raises I/O errors
This Mode Opens file for writing.
‘wb’ Write only If file does not exist, it creates a new file.
If file exists it truncates the file.
File is in write mode only, new data will be added to
‘ab’ Append the end of existing data i.e. no overwriting. If file not
exists it creates a new file
Read and File must exists otherwise error is raised Both reading
‘r+b’ or ‘ rb+’
write and writing can take place
Write and File is created if not exists, if exists data will be
‘w+b’ or ’wb+’
read truncated, both read and write allowed
Write and Same as above but previous content will be retained
‘a+b’ or ‘ab+’
read and both read and write.

Page 3 of 16 Website: https://www.learnpython4cbse.com/


About Us Website: https://www.learnpython4cbse.com/ Feedback
eedback 8076665624

Learnpython4cbse Youtube Channel:


Inspiring Success SuperNova-learnpython
learnpython
PYTHON ONLINE CLASSES COMPUTER SC. INFORMATICS PRAC. SAMPLE PAPERS PYTHON MCQs

Opens a file for exclusive creation. If the file already


‘xb’ Write
exists, the operation fails.
Write and Similar to w+ as it will create a new file if the file does
‘xb+’
read not exist. Otherwise, will raise FileExistsError.

Creating / Opening / Closing Binary Files:

A binary file is opened in the same way as open text file but make sure to use ‘b’ with file modes
to open a file in binary mode.

Example: To open a file ‘Mydoc.dat’ in write mode


mode.

‘wb’) # Binary file open in write mode


MyFile = open ("Mydoc.dat", ‘wb’
with file handle as Myfile

Example: To open a file ‘Mydoc.dat’ in read mode

‘rb’) # Binary file open in read mode


MyFile = open ("Mydoc.dat", ‘rb’
with file handle as Myfile

Note: If you are opening a binary file in the read mode, then the file must exist otherwise an
exception is raised.

Closing Binary file

An open binary file is closed in the sane way as close any other file.

Syntax:

Filehandle.close()

Example: To close the file ‘Mydoc.dat’

Myfile.close()

Page 4 of 16 Website: https://www.learnpython4cbse.com/


About Us Website: https://www.learnpython4cbse.com/ Feedback
eedback 8076665624

Learnpython4cbse Youtube Channel:


Inspiring Success SuperNova-learnpython
learnpython
PYTHON ONLINE CLASSES COMPUTER SC. INFORMATICS PRAC. SAMPLE PAPERS PYTHON MCQs

Writing Instance onto a file –Using


Using pickle.dump()
• In order to write an object on to a binary file opened in the write mode, you should use
dump() function of pickle module
module.
Syntax of dump ():

pickle.dump (object_to_be_written, fileObject)

Example 1:

Example 2: Write a program to get Employee(empno,ename,sal) from user using dictionay and
write onto a binary file.

Page 5 of 16 Website: https://www.learnpython4cbse.com/


About Us Website: https://www.learnpython4cbse.com/ Feedback
eedback 8076665624

Learnpython4cbse Youtube Channel:


Inspiring Success SuperNova-learnpython
learnpython
PYTHON ONLINE CLASSES COMPUTER SC. INFORMATICS PRAC. SAMPLE PAPERS PYTHON MCQs

Example 3: Write a program to get Employee(empno,ename,sal) from user using List and write
onto a binary file.

Reading from a Binary File –Using


Using pickle.load
pickle.load()
• For reading data from a binary file, we have to use pickle.load () to read the object from
pickled file.
Syntax:
Object=pickle.load(filehandle)

Example 1: To read the data from the file ‘emp.dat’.

Page 6 of 16 Website: https://www.learnpython4cbse.com/


About Us Website: https://www.learnpython4cbse.com/ Feedback
eedback 8076665624

Learnpython4cbse Youtube Channel:


Inspiring Success SuperNova-learnpython
learnpython
PYTHON ONLINE CLASSES COMPUTER SC. INFORMATICS PRAC. SAMPLE PAPERS PYTHON MCQs

Example 2: Write a program to open the file ‘Samplelist.dat’,


‘Samplelist.dat’ read
the object written in it and display.

OUTPUT

Searching in a Binary File:


In order to search for some value(s) in a file, need to follows the given steps:

1. Open the file in read mode.

2. Read the file contents record by record

3. In every read record, look for the desired search


search-key

4. If found, process as desired.

5. If not found, read the next record and look for the desired serach key.

6. If search- key is not found in any of the rrecords,


ecords, report that no such value found in the file.

Page 7 of 16 Website: https://www.learnpython4cbse.com/


About Us Website: https://www.learnpython4cbse.com/ Feedback
eedback 8076665624

Learnpython4cbse Youtube Channel:


Inspiring Success SuperNova-learnpython
learnpython
PYTHON ONLINE CLASSES COMPUTER SC. INFORMATICS PRAC. SAMPLE PAPERS PYTHON MCQs

Example: Write a program to open file ‘Samplelist.dat’ and search the record for given name. If
found, display the record.

Append data in Binary File:


To append records in a binary file, make sure to open the file in append mode (‘ab’
or ‘ab+’)

Page 8 of 16 Website: https://www.learnpython4cbse.com/


About Us Website: https://www.learnpython4cbse.com/ Feedback
eedback 8076665624

Learnpython4cbse Youtube Channel:


Inspiring Success SuperNova-learnpython
learnpython
PYTHON ONLINE CLASSES COMPUTER SC. INFORMATICS PRAC. SAMPLE PAPERS PYTHON MCQs

tell( ) and seek( ) methods:


tell( ): When you open a file in reading/writing mode, the file pointer rests at 0th byte.
When you open a file in append mode, the file pointer rests at last byte.
byte
It returns the current position of cursor in file.
EXAMPLE:

OUTPUT: 14
seek (offset, from _what) : seek() function is used to change the position of the file handle
(file pointer) to a given specific position. File pointer is like a cursor, which defines from
where the data has to be read or written in the file.
Change the cursor position by bytes as specified by the offset.
f.seek(–10,1)
10,1) from current position, move 10 bytes backward
f.seek(10,1) from current position, move 10 bytes forward
f.seek(–20,1)
20,1) from current position, move 20 bytes backward
f.seek(10,0) from beginning of file, move 10 bytes forward
Example:
The reference point is defined by the
"from_what" argument. It can have any of the
three values:
0: sets the reference point at the beginning of
the file, which is by default.
1: sets the reference point at the current file
position.
2: sets the reference point at the end of the file.
OUTPUT: 5
Updating in a Binary File:

Three Step processs to update record in binary file


Locate the record to be updated by searching for it

Page 9 of 16 Website: https://www.learnpython4cbse.com/


About Us Website: https://www.learnpython4cbse.com/ Feedback
eedback 8076665624

Learnpython4cbse Youtube Channel:


Inspiring Success SuperNova-learnpython
learnpython
PYTHON ONLINE CLASSES COMPUTER SC. INFORMATICS PRAC. SAMPLE PAPERS PYTHON MCQs

Make changes in the loaded record in memeory (the read record)


Write back onto the file at the exact location of old record.
Example: Write a Program to update the records of the ‘sample.dat’ so that those who have
salary more than 30000 , get additional bonus of Rupees - 2000.

To open the file in read as well as write mode: rb+

Before reading any record, firstly store its


beginning position (exact position)

Changes made in the record; Rupees 2000 added

Place the file pointer at the exact location of the record

Write the updated record on the exact location

OUTPUT

Page 10 of 16 Website: https://www.learnpython4cbse.com/


About Us Website: https://www.learnpython4cbse.com/ Feedback
eedback 8076665624

Learnpython4cbse Youtube Channel:


Inspiring Success SuperNova-learnpython
learnpython
PYTHON ONLINE CLASSES COMPUTER SC. INFORMATICS PRAC. SAMPLE PAPERS PYTHON MCQs

Previous Years Questions


Q1. A binary file “vehicle.dat” has structure [RegNo, Type, Make, Year].

a. Write a user defined function AddVahan() to input data for a vehicle and add to
“vehicle.dat” file.

b. Write a function CountVahan(Type) in Python which accepts the Type of the vehicle as the
parameter and count and return the number of vehicles of the given Type.

Q2. Write a method/function COSTLY() in python to search and display Name and Price from a
pickled file STOCK.DAT, where Price of the items are more than 1000. (BOARD 2019)

Q3. A binary file “player.dat” has structure (PlayerId, Name, Team, and StrikeRate).
StrikeRate

Write a function ShowPlayer() in Python that would read contents of the file and display the
details of those players whose Team
eam is “India” and StrikeRate is above 50. Also display the
total number of such players.

Q4. Write a function, copyData(), that reads contents from the file SPORT.DAT and copies the
Basket Ball
records with Sport name as “Basket Ball”” to the file named BASKET.DAT. The
Th function should
return the total number of records copied to the file BASKET.DAT. (CBSE SAMPLE PAPER –
2023-24)

Q5. A Binary file, CINEMA.DAT has the following structure


[MNO, MNAME, MTYPE]
Where
MNO – Movie Number
MNAME – Movie Name
MTYPE is Movie Type
Write a user defined function, findType (mtype) that accepts mtype as parameter and displays
all the records from
rom the binary file CINEMA.DAT that have the value of Movie Type as mtype.
(CBSE SAMPLE PAPER – 2023-24)
Q6: Shreyas is a programmer, who has recently been given a task to write a user defined
function named write_bin() to create a binary file called Cust_file.dat containing customer

Page 11 of 16 Website: https://www.learnpython4cbse.com/


About Us Website: https://www.learnpython4cbse.com/ Feedback
eedback 8076665624

Learnpython4cbse Youtube Channel:


Inspiring Success SuperNova-learnpython
learnpython
PYTHON ONLINE CLASSES COMPUTER SC. INFORMATICS PRAC. SAMPLE PAPERS PYTHON MCQs

information - customer number (c_no), name (c_name), quantity (qty), price (price) and
amount (amt) of each customer.
The function accepts customer number, name, quantity and price. Thereafter, it displays the
message ‘Quantity less than 10…. Cannot SAVE', if quantity entered is less than 10. Otherwise
unt as price * quantity and then writes the record in the form of a
the function calculates amount
list into the binary file. (CBSE BOARD EXAM – 2022-23)

(i) Write the correct statement to open a file ’Cust_file.dat’ for writing the data of the customer.
(ii) Which statement should Shreyas fill in Statement 2 to check whether quantity is less than
10?
(iii) Which statement should Shreyas fill in Statement 3 to write data to the binary file and in
Statement 4 to stop further processing if the user does not wish to enter more records?
records

Page 12 of 16 Website: https://www.learnpython4cbse.com/


About Us Website: https://www.learnpython4cbse.com/ Feedback
eedback 8076665624

Learnpython4cbse Youtube Channel:


Inspiring Success SuperNova-learnpython
learnpython
PYTHON ONLINE CLASSES COMPUTER SC. INFORMATICS PRAC. SAMPLE PAPERS PYTHON MCQs

OR
(Option for part (iii) only)
(iii) What should Shreyas fill in Statement 5 to close the binary’ file named Cust_file.dat and in
Statement 6 to call a function
on to write data in binary file
file?
Q7. (i) Differentiate between 'w' and 'a' file modes in Python. (CBSE BOARD - 2023-24)

(ii) Consider a binary file, items.dat, containing records stored in the given format:

{item id: [item name,amount]} .Write


Write a function, Copy_new(), that copies all records whose
amount is greater than 1000 from items . dat to new items . dat.

Q1. Solution

Page 13 of 16 Website: https://www.learnpython4cbse.com/


About Us Website: https://www.learnpython4cbse.com/ Feedback
eedback 8076665624

Learnpython4cbse Youtube Channel:


Inspiring Success SuperNova-learnpython
learnpython
PYTHON ONLINE CLASSES COMPUTER SC. INFORMATICS PRAC. SAMPLE PAPERS PYTHON MCQs

Q2: Solution

Q3. Solution

Q4: Solution

Page 14 of 16 Website: https://www.learnpython4cbse.com/


About Us Website: https://www.learnpython4cbse.com/ Feedback
eedback 8076665624

Learnpython4cbse Youtube Channel:


Inspiring Success SuperNova-learnpython
learnpython
PYTHON ONLINE CLASSES COMPUTER SC. INFORMATICS PRAC. SAMPLE PAPERS PYTHON MCQs

Q5: Solution

Q6: Solution

i) Statement 1: open ("Cust file.dat", "wb")

ii) Statement 2: qty<10 :

iii) Statement 3: pickle, dump (c detail ,bin file)


Statement 4: break

OR

iii) Statement 5: bin file.close()


Statement 6: write_bin()

Q7: Solution (i)

'w' 'a'
Open the file in write mode. Open the file in append mode.
If the file doesn’t exist, then a new file will If the file doesn’t exist, then a new file
be created. will be created.
The file pointer is in the beginning of the file. The file pointer is at the end of the file.
If the file exists, the contents of tthe file, if If the file exists, the new data is added at
any, are lost/truncated and the new data is the end of the file without deleting the
added as fresh data into the file. previous contents of the file.

Page 15 of 16 Website: https://www.learnpython4cbse.com/


About Us Website: https://www.learnpython4cbse.com/ Feedback
eedback 8076665624

Learnpython4cbse Youtube Channel:


Inspiring Success SuperNova-learnpython
learnpython
PYTHON ONLINE CLASSES COMPUTER SC. INFORMATICS PRAC. SAMPLE PAPERS PYTHON MCQs

Q7 ii)

OR

Page 16 of 16 Website: https://www.learnpython4cbse.com/

You might also like