Data File Handling - Binary File
Data File Handling - Binary File
com/ Feedback
eedback 8076665624
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
• 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.
• 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.
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.
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.
Note: If you are opening a binary file in the read mode, then the file must exist otherwise an
exception is raised.
An open binary file is closed in the sane way as close any other file.
Syntax:
Filehandle.close()
Myfile.close()
Example 1:
Example 2: Write a program to get Employee(empno,ename,sal) from user using dictionay and
write onto a binary file.
Example 3: Write a program to get Employee(empno,ename,sal) from user using List and write
onto a binary file.
OUTPUT
5. If not found, read the next record and look for the desired serach key.
Example: Write a program to open file ‘Samplelist.dat’ and search the record for given name. If
found, display the record.
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:
OUTPUT
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)
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
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:
Q1. Solution
Q2: Solution
Q3. Solution
Q4: Solution
Q5: Solution
Q6: Solution
OR
'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.
Q7 ii)
OR