File Handling: Binary Files

Vijaya Kumar Chinthala
Analytics Vidhya
Published in
3 min readNov 9, 2020

--

Serialization (Also called Pickling): The process of converting Python object hierarchy into byte stream so that it can be written into a file.

De-Serialization (Also called Unpickling): The inverse of Pickling where a byte stream is converted into an object hierarchy. Unpickling produces the exact copy of original object.

  1. First import pickle module
  2. Use dump( ) and load( ) methods of pickle module to perform read and write operations on binary file.

File Opening Modes:

wb writing only. Overwrites the binary file if exists. If not, creates a new binary file for writing.

wb+ both writing and reading. Overwrites the binary file if exits. If not, creates a new binary file for writing.

rb reading only. Sets file pointer at the beginning of the binary file.

rb+ both reading and writing. Sets file pointer at the beginning of the binary file

ab for appending. Move file pointer at end of the binary file. Creates new file for writing, if not exist

ab+ for both appending and reading. Move file pointer at end. If the binary file does not exist, it creates a new file for reading and writing.

  1. Writing onto a Binary File : Pickling

Output:

2. Write a program to open the file EMP.dat(Created in previous program), read the objects written in it and display them.

Output:

3. Write a program to append two employee records to file created in previous program by getting data from the user.

Output:

Accessing and manipulating location of file pointer:

Python provides two functions to manipulate the position of file pointer and thus user can read and write from desired position.

The tell( ) function:

The tell( ) function returns the current position of the file pointer in the file.

<fileobject>.tell( )

The seek( ) function:

The seek ( ) function changes the position of the file pointer by placing the file pointer at the specified position in the open file.

<fileobject>.seek( offset[,mode])

where

offset =======>is number specifying number of bytes

mode =======> is number 0 or 1 or 2

0 for beginning of file

1 current position of file pointer

2 end of file

4. Write a program to open the file EMP.dat(Created in previous program), read and modify the name empno1207 to new vijay7 and display them.

Output:

--

--