Working with binary files in Python

Working with binary files in Python

In this article, I am going to discuss Working with binary files in Python with examples. Please read our previous article where we discussed Files in Python. As part of this article, we are going to discuss the following pointers in details which are related to binary files in Python.

  1. Working with binary files in Python
  2. Working with csv files in Python
  3. ZIPPING and UNZIPPING Files in Python
  4. Working with Directories in Python
  5. Pickling and Unpickling in Python
Working with binary files in Python:

It is very common requirement to read or write binary data like images, video files, audio files etc.

Program: Binary data (demo14.py)

f1=open("thor.jpeg", "rb")
f2=open("newpic.jpeg", "wb")
bytes=f1.read()
f2.write(bytes)
print("New Image is available with the name: newpic.jpg")

Output: Working with binary files in Python

Working with csv files in Python

Csv means Comma separated values. As the part of programming, it is a very common requirement to write and read data wrt csv files. Python provides a csv module to handle csv files.

Program: CSV Files (demo15.py)

import csv
with open("emp.csv", "w", newline='') as f:
   w=csv.writer(f)
   w.writerow(["EMP NO","EMP NAME","EMP SAL","EMP ADDR"])
   n=int(input("Enter Number of Employees:"))
   for i in range(n):
       eno=input("Enter Employee No:")
       ename=input("Enter Employee Name:")
       esal=input("Enter Employee Salary:")
       eaddr=input("Enter Employee Address:")
       w.writerow([eno, ename, esal, eaddr])
print("Total Employees data written to csv file successfully")

Output:

Working with csv files in Python

File: emp.csv content

ZIPPING and UNZIPPING Files in Python:

It is a very common requirement to zip and unzip files. The main advantages are:

  1. To improve memory utilization
  2. We can reduce transfer time
  3. We can improve performance.

To perform zip and unzip operations, Python contains one in-bulit module ‘zipfile’. This module contains a class ZipFile which we are going to use in the examples.

Creating a ZipFile in Python:

We have to create an object to the ZipFile class with the name which we want to give to the zip file, and the mode and a constant ZIP_DEFLATED. This constant represents we are creating a zip file.

Syntax: f = ZipFile(“files.zip”, “w”, “ZIP_DEFLATED”)

Once we are done with creating ZipFile object, we can add files by using write() method f.write(filename)

Program: Zip file in Python(demo16.py)

from zipfile import *
f=ZipFile("files.zip", 'w', ZIP_DEFLATED)
f.write("abc.txt")
f.write("thor.jpeg")
f.write("names.txt")
f.close()
print("files.zip file created successfully")

Output: Creating a ZipFile in Python

You can now check the current directory for the file with name ‘file.zip’ and it will be there.

To perform unzip operation in Python:

We need to create an object in the same way as we did for zipping the file. But the argument values here are different.

f = ZipFile(“files.zip”, “r”, ZIP_STORED)

ZIP_STORED represents unzip operation. This is the default value and hence it will be okay even if we haven’t specified.

Once we created ZipFile object for unzip operation, we can get all file names present in that zip file by using namelist() method

Program: Unzipping in Python(demo17.py)

from zipfile import *
f=ZipFile("files.zip", 'r', ZIP_STORED)
names=f.namelist()
for name in names:
   print( "File Name: ",name)

Output:

Unzipping in Python

Working with Directories in Python:

When working with file system, the common requirements other than operations on the file, we come through are:

  1. To know current working directory
  2. To create a new directory
  3. To remove an existing directory
  4. To rename a directory
  5. To list contents of the directory etc…

To achieve the above requirements, in python, we can use the ‘os’ module. It contains several functions to perform directory related operations.

Program: OS Module Example (demo18.py)

import os
cwd=os.getcwd()
print("Current Working Directory:" ,cwd)

Output: Working with Directories in Python

Program: Working with Directories in Python (demo19.py)
import os
os.mkdir("mysub")
print("mysub directory created in current working directory")

Output: OS Module Example

You can now check for a folder with name ‘sub1’ in your current working directory

Program: Create multiple directories in Python (demo20.py)
import os
os.makedirs("sub1/sub2/sub3")
print("sub1 and in that sub2 and in that sub3 directories created")

Output: Create multiple directories in Python

Program: Removing a Directory in Python (demo21.py)
import os
os.rmdir("mysub")
print("mysub2 directory deleted")

Output: Removing a Directory in Python

Program: Removing all Directories in Python (demo22.py)

import os
os.removedirs("sub1/sub2/sub3")
print("All 3 directories sub1,sub2 and sub3 removed")

Output: Removing all Directories in Python

Pickling and Unpickling in Python:

Sometimes we have to write the total state of the object to the file and we have to read the total object from the file. The process of writing the state of an object to the file is called pickling and the process of reading the state of an object from the file is called unpickling.

We can implement pickling and unpickling by using the pickle module of Python. Pickle module contains a dump() function to perform pickling and pickle module contains load() function to perform unpickling

pickle.dump(object, file)

obj=pickle.load(file)

Program: Pickling and Unpickling in Python (demo23.py)
import pickle
class Employee:
   def __init__(self, eno, ename, esal, eaddr):
       self.eno=eno
       self.ename=ename
       self.esal=esal
       self.eaddr=eaddr
   def display(self):
       print(self.eno,"\t", self.ename,"\t", self.esal,"\t",self.eaddr)

with open("emp.dat","wb") as f:
   e=Employee(100,"Nireekshan",1000,"Hyd")
   pickle.dump(e,f)
   print("Pickling of Employee Object completed...")
with open("emp.dat","rb") as f:
   obj=pickle.load(f)
   print("Printing Employee Information after unpickling")
   obj.display()

Output:

Pickling and Unpickling in Python

In the next article, I am going to discuss Regular Expression in Python with Examples. Here, in this article, I try to explain Working with Binary Files in Python with Examples. I hope you enjoy this Binary Files in Python article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *