Data File Handling | Computer Science Class 12 | Binary File | Read and Write Method | Python | Board exam 2025 | Notes | Study Material

 

Data File Handling (Working With Binary files)

Binary Files

- A binary files stores in the form of a stream of BYTES

- Non-textual data

- Not human-readable

- Requires specific software or hardware to interpret

- Can store complex data types, such as images, audio, and video

- Often smaller in size compared to text files

 Sterilization(Picking)

This is the process of converting python object hierarchy into a byte stream.So that it can be written into a file.picking converts an object in byte stream in such a way that it can be reconstructed in original form when unpickling or die-serialization.

Picking =====Object-bytes

Unpicking====Bytes-object

 


Unpickling:

This is  inverse of pickling where a byte stream is converted into an object hierarchy. Unpicking produces the exact replica of the original object.

Syntax

import pickle

Pickle is an module

You may use dump() and load() methods of pickle to write and read from an open binary file respectively.

I) Import pickle module

II) Open binary file in the required file mode (read mode or write mode)

III) Process binary file by writing/reading objects using pickle modules methods.

IV) Once done,close the file.

Creating /opening /closing Binary files

file=open(“student.dat”,”wb+”)

file.close()

Write onto a Binary File

dump()

Syntax:

pickle.dump(<object-to-be-written>,<filehandle-of -open -file>)

Example:

pickle.dump(emp1,file)

For example:

import pickle

emp1={'empno':1201,'Name':'zoya','Age':25}

empfile=open('Emp.dat','wb')

pickle.dump(emp1,empfile)

print("File Created")

empfile.close()

Output:

€}q (X   empnoqM±X   NameqX   zoyaqX   AgeqK_x0019_u.

 

Read onto a Binary File: load()

Syntax:

pickle.load(<file_handle>)

For example:

import pickle

emp={}

empfile=open("Emp.dat","rb")

try:

    while True:

        emp=pickle.load(empfile)

        print(emp)

except EOFError:

empfile.close()

Output:


 Updating in a Binary files:

   Changing its values and storing it again.

Updating records in a file similar and is a three-step process.

1. Locate the record to be updated by searching for it.

2. Make changes in the loaded record in memory (the read mode)

3. Write back onto the file at the exact location of old record.

 


Post a Comment

0 Comments