Skip to main content

GRADE XII - BINARY FILES | 22 Aug

 

Write & Read a List to a Binary File

import pickle

my_list = [10, 20, 30, 40, 50]

file = open("data.dat", "wb")  # open file in write-binary mode

pickle.dump(my_list, file)     # write the list to the file

file.close()                   # don't forget to close the file

print("List successfully written to binary file.")

read-binary mode

file = open("data.dat", "rb")   # open file in read-binary mode

loaded_list = pickle.load(file)  # read the list from the file

file.close()

print("List read from binary file:", loaded_list)


Notes:

  • wb = write binary
  • rb = read binary
  • pickle.dump(obj, file) → writes object to file

pickle.load(file) → reads object from file


Write a Dictionary to a Binary File

import pickle

# Dictionary to write

my_dict = {

    "name": "Pooja",

    "age": 25,

    "city": "Delhi"

}

# Open file in write-binary mode

file = open("data.dat", "wb")

pickle.dump(my_dict, file)  # Serialize and write dictionary

file.close()

print("Dictionary successfully written to binary file.")

 

file = open("data.dat", "rb")

loaded_dict = pickle.load(file)  # Deserialize

file.close()

print("Dictionary read from file:", loaded_dict)

EG: DUMP & LOAD USING BINARY FILE

import pickle

file = open("stud.dat", "wb")

while True:

    rno = int(input("\nEnter roll no - "))

    name = input("Enter name - ")

    perc = float(input("Enter percentage - "))

    stream = input("Enter stream - ")

    dets = [rno, name, perc, stream]

    pickle.dump(dets, file)

 

    ans = input("Want to enter another (y/n) - ")

    if ans in "nN":

        break

file.close()

print("Student records saved successfully.")

 

file = open("stud.dat", "rb")

print("Student Records:\n")

while True:

    try:

        record = pickle.load(file)  # Load one record at a time

        print("Roll No:", record[0])

        print("Name:", record[1])

        print("Percentage:", record[2])

        print("Stream:", record[3])

        print("-" * 30)

    except EOFError:

        break  # End of file reached

file.close()

28th July 2025

Eg: Updated Code to Add Multiple Records Without Overwriting:

import pickle

file = open("stud.dat", "ab")  # Append binary mode

while True:

    rno = int(input("\nEnter roll no - "))

    name = input("Enter name - ")

    perc = float(input("Enter percentage - "))

    stream = input("Enter stream - ")

     dets = [rno, name, perc, stream]

    pickle.dump(dets, file)

    ans = input("Want to enter another (y/n) - ")

    if ans in "nN":

        break

file.close()

print("Student records added successfully.")

 

READ FILE :

try:

    file = open("stud.dat", "rb")  # Open in read-binary mode

    print("Student Records:\n")

    while True:

        try:

            record = pickle.load(file)  # Load one record at a time

            print("Roll No:", record[0])

            print("Name:", record[1])

            print("Percentage:", record[2])

            print("Stream:", record[3])

            print("-" * 30)

        except EOFError:

            break  # End of file reached

    file.close()

except FileNotFoundError:

    print("File not found. Please make sure 'stud.dat' exists.")


Q1. a)WAP that reads a binary file “emp” and display all records of employee one by one.

       b) Display all records who are getting salaries between 2500  and 300

Sol:

import pickle

my_list = [100, 202, 300, 400, 500]

# Write the list to a binary file

with open("data.dat", "wb") as file:

    pickle.dump(my_list, file)

print("List successfully written to binary file.")

 

f1=open("data.dat", "rb")

e=pickle.load(f1)

for x in e:

     print(x)

f1.close()

PART B

f1=open("data.dat", "rb")

e=pickle.load(f1)

for x in e:

        if x >= 200 and x <= 400:

        print(x)

Q2.

1. A file, PASSENGERS.DAT, stores the records of passengers using the following structure:

[PNR, PName, BRDSTN, DESTN, FARE]

Where:

·       PNR – Passenger Number (string type)

·       PName – Passenger Name (string type)

·       BRDSTN – Boarding Station Name (string type)

·       DESTN – Destination Station Name (string type)

·       FARE – Fare amount for the journey (float type)

Write user-defined functions in Python for the following tasks:

a)     Create() – to input data for passengers and write it in the binary file PASSENGERS.DAT.

b)    SearchDestn(D) – to read contents from the file PASSENGERS.DAT and display the details of those passengers whose DESTN matches with the value of D.

c)     UpdateFare() – to increase the fare of all passengers by 5% and rewrite the updated records into the file PASSENGERS.DAT.

 

  2. Consider a binary file, items.dat, containing records stored in the given format:

{item_id: [item_name, amount]}

Write a function, Copy_new(), that copies all records whose amount is greater than 1000 from items.dat to new_items.dat.

 

3. A binary file, EMP.DAT, has the following structure:

[Emp_Id, Name, Salary]

Where:

  • Emp_Id : Employee ID
  • Name : Employee Name
  • Salary : Employee Salary

Write a user-defined function disp_Detail() that would read the contents of the file EMP.DAT and display the details of those employees whose salary is below 25000.

 4. A binary file named “TEST.dat” has some records of the structure:

[TestId, Subject, MaxMarks, ScoredMarks].

Write a function in Python named DisplayAvgMarks(Sub) that will accept a subject as an argument and read the contents of TEST.dat. The function will calculate & display the Average of the ScoredMarks of the passed Subject on screen.

  

SOLUTIONS

 1. A file, PASSENGERS.DAT, stores the records of passengers using the following structure:

[PNR, PName, BRDSTN, DESTN, FARE]

Where:

  • PNR – Passenger Number (string type)
  • PName – Passenger Name (string type)
  • BRDSTN – Boarding Station Name (string type)
  • DESTN – Destination Station Name (string type)
  • FARE – Fare amount for the journey (float type)

Write user-defined functions in Python for the following tasks:

a)     Create() – to input data for passengers and write it in the binary file PASSENGERS.DAT.

b)    SearchDestn(D) – to read contents from the file PASSENGERS.DAT and display the details of those passengers whose DESTN matches with the value of D.

c)     UpdateFare() – to increase the fare of all passengers by 5% and rewrite the updated records into the file PASSENGERS.DAT.

Sol.

        import pickle

 

# a) Function to create and write passenger data

def Create():

    with open("PASSENGERS.DAT", "wb") as file:

        while True:

            pnr = input("Enter PNR: ")

            pname = input("Enter Passenger Name: ")

            brdstn = input("Enter Boarding Station: ")

            destn = input("Enter Destination Station: ")

            fare = float(input("Enter Fare: "))

            record = [pnr, pname, brdstn, destn, fare]

            pickle.dump(record, file)

           

            choice = input("Add another record? (y/n): ")

            if choice.lower() != 'y':

                break

 

# b) Function to search passengers by destination

import pickle

 

def SearchDestn(D):

    try:

        with open("PASSENGERS.DAT", "rb") as file:

            count = 0  # Counter for matching records

            while True:

                try:

                    record = pickle.load(file)

                    if record[3].lower() == D.lower():

                        print("PNR:", record[0])

                        print("Name:", record[1])

                        print("Boarding:", record[2])

                        print("Destination:", record[3])

                        print("Fare:", record[4])

                        print("-" * 30)

                        count += 1

                except EOFError:

                    break

            if count == 0:

                print("No passengers found with destination:", D)

    except FileNotFoundError:

        print("PASSENGERS.DAT file not found.")

 

# c) Function to update fare by 5%

def UpdateFare():

    try:

        updated_records = []

        with open("PASSENGERS.DAT", "rb") as file:

            while True:

                try:

                    record = pickle.load(file)

                    record[4] *= 1.05  # Increase fare by 5%

                    updated_records.append(record)

                except EOFError:

                    break

 

        with open("PASSENGERS.DAT", "wb") as file:

            for rec in updated_records:

                pickle.dump(rec, file)

        print("Fare updated successfully for all passengers.")

 

    except FileNotFoundError:

        print("File not found.")

 

 2. Consider a binary file, items.dat, containing records stored in the given format:

{item_id: [item_name, amount]}

Write a function, Copy_new(), that copies all records whose amount is greater than 1000 from items.dat to new_items.dat.

 

Sol.

import pickle

 def Copy_new():

    try:

        with open("items.dat", "rb") as infile, open("new_items.dat", "wb") as outfile:

            while True:

                try:

                    record = pickle.load(infile)

                    # Check each item in the dictionary

                    for item_id, value in record.items():

                        item_name, amount = value

                        if amount > 1000:

                            pickle.dump({item_id: value}, outfile)

                except EOFError:

                    break

    except FileNotFoundError:

        print("File not found.")

 

3. A binary file, EMP.DAT, has the following structure:

[Emp_Id, Name, Salary]

Where:

  • Emp_Id : Employee ID
  • Name : Employee Name
  • Salary : Employee Salary

Write a user-defined function disp_Detail() that would read the contents of the file EMP.DAT and display the details of those employees whose salary is below 25000.

 Sol.

import pickle

def disp_Detail():

    try:

        with open("EMP.DAT", "rb") as file:

            print("Employees with salary below 25000:")

            while True:

                try:

                    emp = pickle.load(file)

                    if emp[2] < 25000:

                        print("Emp_ID:", emp[0], ", Name:", emp[1], ", Salary:", emp[2])

                except EOFError:

                    break

    except FileNotFoundError:

        print("EMP.DAT file not found.")

 DICTIONARY METHOD:

import pickle

def add_Employee():

    file = open("EMP.DAT", "ab")   # append binary mode

    ch = 'y'

        while ch.lower() == 'y':

        emp = {}

        emp["Emp_Id"] = int(input("Enter Employee ID: "))

        emp["Name"] = input("Enter Name: ")

        emp["Salary"] = float(input("Enter Salary: "))

                pickle.dump(emp, file)

                ch = input("Add more records? (y/n): ")

     file.close()


def disp_Detail():

    try:

        with open("EMP.DAT", "rb") as file:

            print("Employees with salary below 25000:")

            while True:

                try:

                    emp = pickle.load(file)   # emp is a dictionary

                    if emp["Salary"] < 25000:

                        print("Emp_ID:", emp["Emp_Id"], ", Name:", emp["Name"], ", Salary:", emp["Salary"])

                except EOFError:

                    break

    except FileNotFoundError:

        print("EMP.DAT file not found.")


4. 4. A binary file named “TEST.dat” has some records of the structure:

 [TestId, Subject, MaxMarks, ScoredMarks].

Write a function in Python named DisplayAvgMarks(Sub) that will accept a subject as an argument and read the contents of TEST.dat. The function will calculate & display the Average of the ScoredMarks of the passed Subject on screen.

 Sol.

import pickle

def DisplayAvgMarks(Sub):

    try:

        with open("TEST.dat", "rb") as file:

            total = 0

            count = 0

            while True:

                try:

                    record = pickle.load(file)

                    if record[1].lower() == Sub.lower():  # Match subject

                        total += record[3]  # ScoredMarks

                        count += 1

                except EOFError:

                    break


        if count > 0:

            avg = total / count

            print("Average Scored Marks in", Sub, "=", round(avg, 2))

        else:

            print("No records found for subject:", Sub)


    except FileNotFoundError:

        print("TEST.dat file not found.")

Comments

Popular posts from this blog

GRADE XII - Python Connectivity with MySQL

  Python Connectivity with MySQL In real-life applications, the data inputted by the user and processed by the application needs to be saved permanently, so that it can be used for future manipulation. Usually, input and output data is displayed during execution but not stored, as it resides in main memory , which is temporary — i.e., it gets erased once the application is closed. This limitation can be overcome by sending the data to be stored in a database , which is made accessible to the user through a Front-End interface . Key Concepts Database A database is an organized collection of data that is stored and accessed electronically from a computer system. DBMS (Database Management System) A DBMS is software that interacts with end-users, applications, and the database to capture and analyze data. Front-End The Front-End is the user interface of the application, responsible for input/output interaction with the user. Back-End The Back-End refe...

GRADE XII - CSV FILE

CSV FILE (COMMA SEPERATED VALUE) CSV NOTES LINK :  CSV NOTES - CLICK HERE Writing data to a CSV file involves the following steps: Import the csv module Open the CSV file in write mode ( "w" ) using open() Create the writer object Write the data into the file using the writer object Close the file using close() writerow() Method This method is used to write a single row to a CSV file. It takes a sequence (list or tuple) as its parameter, and writes the items as a comma-separated line in the file. You do not need to add a newline character (\n) — it automatically places the end-of-line marker.     EXAMPLE 1: import csv  # Importing the csv module # CSV file opened using relative path csv_fobj = open("emp.csv", "w")   # Writer object created wtr_obj = csv.writer(csv_fobj) # Record with field heading is written wtr_obj.writerow(["Empno", "Name", "Salary"]) # Records with data are...