How to make a binary file 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: 

How to make a binary file 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:

How to make a binary file in Python?

File: emp.csv content

How to make a binary file in Python?

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: 

How to make a binary file 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:

How to make a binary file 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: 

How to make a binary file in Python?

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

Output: 

How to make a binary file in Python?

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: 

How to make a binary file in Python?

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

Output: 

How to make a binary file 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: 

How to make a binary file 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:

How to make a binary file 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.

How do I create a binary file in Python?

Write Bytes to File in Python Example 1: Open a file in binary write mode and then specify the contents to write in the form of bytes. Next, use the write function to write the byte contents to a binary file.

How to create a binary file?

How to Create Binary Files.
Add the namespace to the code page of your project. Writing and reading files requires the "IO" namespace. ... .
Create the filestream variable and assign it to a binary stream. ... .
Write to the binary file using the "Write" function. ... .
Close the file once all the information has been saved to the file..

How do I convert a file to binary?

How to Convert Text Files to Binary.
Open the text file in Notepad. ... .
Right-click on the highlighted text and click "Copy.".
Right-click inside the Binary Converter text box and click "Paste." The text from the text file is pasted into the Binary Converter input box..

Is Python a binary file?

Python has tools for working with binary files. Binary files use strings of type bytes. This means when reading binary data from a file, an object of type bytes is returned. The binary file is opened using the open() function, whose mode parameter contains the character 'b'.