Binary File in Python Notes for Class 12

  Binary File Handling in Python

  • Binary files store data in binary format (0s and 1s) instead of plain text.
  • Examples: Images, videos, executables, .dat, .bin files.    
Mode Description
'rb' Read binary file
'wb' Write binary file
'ab' Append binary file
'r+' Read and write binary file

    Writing Data to Binary file

  •   Use pickle.dump() to write Python objects in binary form.

      Example:

import pickle
data = {"name": "Ankit", "age": 21}

file = open("data.bin", "wb")
pickle.dump(data, file)
file.close()

    Reading Data from Binary File

  • Use pickle.load() to read data back.

        Example:

import pickle

file = open("data.bin", "rb")
data = pickle.load(file)
print(data)
file.close()

  Appending Data in Binary File

import pickle

file = open("data.bin", "ab")
pickle.dump(["Python", "File", "Binary"], file)
file.close()

       Key Points

  • Always open binary files in binary mode (b).
  • pickle module is used for serializing (writing) and deserializing (reading).
  • Don’t try to open binary files in text editor — data will look like garbage.
  • Use try-except with EOFError to detect end of file.

Important programs

Program to search a word in a text file and display how many times it occurs:

# Open the file in read mode
f = open("data.txt", "r")

# Read file content
text = f.read()

# Input word to search
word = input("Enter the word to search: ")

# Count occurrences
count = text.count(word)

# Display result
print("The word", word, "occurs", count, "times in the file.")

# Close the file
f.close()

Program to write a list of vehicles into a binary file vehicle.dat using the pickle module:

import pickle

# List of vehicles
vehicle = ["Car", "Bus", "Bike", "Truck", "Scooter"]

# Open file in binary write mode
f = open("vehicle.dat", "wb")

# Write list into binary file
pickle.dump(vehicle, f)

# Close the file
f.close()

print("Vehicle list written successfully into vehicle.dat")

Program to write a list of fruits into a binary file fruits.dat using the pickle module:

import pickle

# List of fruits
fruits = ["Apple", "Banana", "Mango", "Orange", "Grapes"]

# Open binary file in write mode
f = open("fruits.dat", "wb")

# Write list into binary file
pickle.dump(fruits, f)

# Close the file
f.close()

print("List of fruits written successfully into fruits.dat")

Count Number of Lines in a File;

f = open("data.txt","r")

count = 0

for line in f:
    count = count + 1

print("Total Lines =",count)

f.close()

Count Vowels in a File

f = open("data.txt","r")

text = f.read()

count = 0

for ch in text:
    if ch.lower() in "aeiou":
        count = count + 1

print("Total Vowels =",count)

f.close()

Leave a Reply

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