Python Tutorial: File Handling-BinaryFile

Thursday, 29 September 2022

File Handling-BinaryFile

Binary files

·         Binary file( used to store binary data such as images, video files, audio files etc.) is a non-text file. It contains data as 1s and 0s (computer readable format).

·         Binary files are processed byte by byte.

·         There is no delimiter and EOL character in the binary file.

·         There is no translations occur in binary files

·         Binary files are faster in processing and consumes less memory compared to text files.

·         Extension of binary files are any non-text file exensions like .bin,.dat etc

·         pickle module is offering functions(dump and load) to operating binary files.

·         File opening mode must attach ‘b’ to it for operating binary file(Ex: ‘rb’- for reading)

Working in Binary files:

Pickle module: pickle module is used in binary file for load( ) and dump( ) methods which are used for reading and writing into binary file respectively.

Pickling/Serialization: It is the process of converting python object into byte stream. Pickling is done at the time of writing into a binary file.

Unpickling/Deserialization: It is the process of converting a byte stream into python object. Unpickling is done at the time reading from a binary file.

pickle Module: - Before reading or writing to a file, we have to import the pickle module.

import pickle

pickle module has two main methods: dump() and load()

pickle.dump() – This method is used to write the object in the file which is opened in ‘wb’ or ‘ab’ i.e. write binary or append binary access mode respectively.

Syntax : pickle.dump(<structure>,<FileObject>)

Here, Structure can be list or dictionary.

FileObject is the file handle of file in which we have to write.

# Simple program to write a list data into a binary file

import pickle

fo = open("binary_file1.dat","wb")

Laptop = ["Dell","HP","ACER"]

pickle.dump(Laptop,fo)

fo.close()

pickle.load() – This method is used to read data from a file and return back into the structure (list/dictionary).

Syntax : <structure> = pickle.load(<FileObject>)

Structure can be any sequence in Python such as list, dictionary etc. FileObject is the file handle of file in which we have to write.

# Program to read data from a binary file

import pickle

fbin = open("binary_file1.dat","rb")

x=pickle.load(fbin)

print(x)

fbin.close()

# Simple program to write a dictionary data into a binary file

import pickle

f=open("my_bin1.bin","wb")

D1={3:'Maruti',2:'Honda',4:'Hundai',1:'BMW'}

pickle.dump(D1,f)

f.close()

f1=open("my_bin1.bin","rb")

D2=pickle.load(f1)

print(D2)

f.close()

BINARY FILE QUESTIONS

Q1. A binary file "Book.dat” has structure [BookNo, Book_Name, Author, Price] 

(a)   Write a user defined function CreateFile() to input data for a record and add to Book.dat.

import pickle

def createFile():

       record=[]

       while True:

                 File=open("BOOK.DAT","ab")

                BookNo=int(input("Enter Book Code : "))

                Book_Name=input("Enter Book Name : ")

                Author=input("Enter Author :")

                Price=float(input("Enter Price :"))

                data=[BookNo,Book_Name,Author,Price]

                record.append(data)

                ch=input("Do you wish to continue continue ..(y/n)")

                if  ch=='n':

                    break    

                pickle.dump(record,File)

        File.close()

(b) Write a function CountRect(Author) in Python which accepts the Author name as parameter and count and return number of books by the given Author are stored in the binary file "Book.dat”.

def CountRec(Author):

    File=open("BOOK.DAT","rb")

    rec=pickle.load(File)

    count=0

    for r in rec:

              if r[2]==Author:

             count=count+1

    File.close()

    return count

 

#main

##createFile()

print('No. of record : ',CountRec('Sumita'))

Q2. A binary file "STUDENT.DAT has structure (admission_number, Name, Percentage). Write a function countrect() in Python that would read contents of the file "STUDENT.DAT” and display the details of those students whose percentage is above 75. Also, display the number of students scoring above 75%.

import pickle as p

def countrec():

    count = 0

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

    while True:

        try:

            record = p.load(file)

            if t[2] > 75:

                    count = count + 1

                    print(record)

        exceptEOFError:

                print("EOF reached !!")

                break

    print("Number student with per  greater than 75%", count)

Q3. A binary file "Lib.dat” has a details of books given below:

List=[BookNo, Book_Name, Author, Price]

(a)   Write a user defined function addBooks() to add more data/records of newpurchase in the existing file "LIB.DAT”.

import pickle

def addBook():

    record=[]

    while True:

        File=open("LIB.DAT","ab")

        BookNo=int(input("Enter Book Code : "))

        Book_Name=input("Enter Book Name : ")

        Author=input("Enter Author :")

        Price=float(input("Enter Price :"))

        data=[BookNo,Book_Name,Author,Price]

        record.append(data)

        ch=input("continue ..")

        if ch=='n':

            break

         pickle.dump(record,File)

        File.close()

 

(b) Write a user defined function in Python which accepts a book no. from a userto search and print the details of it. If no such book exists, then print a relevant message for the user.

def search_book():

    File=open("LIB.DAT","rb")

    Bno=int(input("Enter Book NO :"))

    rec=pickle.load(File)

    found=0

    for r in rec:

        if r[0]==Bno:

            print(r[0],r[1],r[2],r[3],sep='\t')

            found=1

            break

    if found==0:

        print('Record not found')

    File.close()

Q4. For a file "LIB.DAT” containing details of all the books, write a function in Pythonto increase the price by 50/- of each book of "ABP” publisher by using tell andseek function.

Each book contains BookNo, Book_Name, Author, Publisher,Price.

import pickle

def modify_data():

    file=open('LIB.DAT','rb+')

    found=0

    try:

        loc=file.tell()

        record=pickle.load(file)

        for r in record:

                if r[1]=='IP':

                    r[3]=r[3]+50

                file.seek(loc)

        pickle.dump(record,file)

        print("Modified Record")

        found=1

        break

    if found==0:

        print("Record not found")

    file.close()

exceptEOFError:

print("file not found")

Q5. For a binary file TELE.DAT, containing the records of the following List:

Mob_list=[aust_id,cust_name, mobile_no]

Note: mobile no is of type string

Write a function in Python that would read details from a file "TELE.DAT"andmodify the mobile number by 7 which are starting with digit 8.

Q6. For a binary file LIB.DAT, containing the records of the following List:

Library=[b_no, b_name, b_title, b_price]

Write a user defined function to remove a record from a file "LIB.DAT" by using b_no.

import pickle

def bf_delete():

    f = open("LIB.DAT","rb")

    data=pickle.load(f)

    f.close()

    b_no = int(input("Player to code to delete a record:"))

    f = open("LIB.DAT","wb")

    lst=[]

    for record in data:

            if record[0]==b_no:

                    continue

            lst.append(record)

    pickle.dump(lst,f)

    f.close()

Q7. A binary file "TextBook.dat” has structure [SNo, Chapter, page_no]

Write a function copy_book() in Python to copy only even chapters of “Textbook.dat” into another binary file "notebook.dat”.

defcopy_book():

    file1=open("TextBook.dat",'rb')

    file2=open("NoteBook.dat",'wb')

    record1=[]

    record=pickle.load(file1)

    for i in record:

            if i[1]%2==0:

                    record1.append(i)

                    pickle.dump(record1,file2)

file1.close()

file2.close()

Q8. Assuming a binary file "ques_paper.dat" which includes 14 questions.

(a)   Write a user defined function to add one more question as 15thquestion in the existing file "ques_paper.dat".

import pickle

def appendQue():

        file=open(‘ques_paper.dat’, ‘ab’)

        que=input(“Enter Question :”)

        pickle.dump(que,file)

        file.close()

(b)   Write a user defined functions to read a file "ques_paper.dat” and print all the questions on screen.

import pickle

def read_ques():

            file=open(‘ques_paper.dat’, ‘rb’)

            try:

                record=pickle.load(file)

                print(record)

            exceptEOFError:

                pass

            file.close()

Q8. Consider the following definitions of dictionary cust and define a function in Python to search a record by customer number from a binary file "cuntomer.dat”. Print the appropriate message if the record is not found.

Cust={‘cust_no’:______________, ‘cust_name’:______________}

File=open(“customer.dat”, “rb”)

c_no= int(input(“Enter customer no. ”)

try:

            while True:

                        record=pickle.load(file)

                        if record[cust_no]=s_rec:

                                    print(record[cust_no],record[cust_name], sep=’\t’)

except EOFError:

            print(“Record not found…..)

file.close()

 

Q9. Consider the following definition of dictionary cust and define a function inPython to read a file "customer.dat” and print record of customers from a binary file "customer.dat" whose salary is less than 20000/-. Assume that file contains record of 100 customers.

Custs={‘cust_no’:______________, ‘cust_name’:______________, ‘salary’:_________}

def search_data():

            file=open(“customer.dat”, ‘rb’)

            try:

                        while True:

                                    record=pickle.load(file)

                                    if record[salary]<20000:

                                                c_no=record[cust_no]

                                                c_nm=record[cust_name]

                                                c_sal=record[Salary]

                                    print(c_no,c_nm,c_sal, ‘\t’)

            except EOFErorr:

                        print(“Record not found…..”)

            file.close()

 

Q10. Observe the following declaration carefully

Electricity=[kno, consumer, unit_usage, amt_per_unit, tot_amt]

Write a function to generate an electricity bill as per the following criteria and store it in a binary file "electricity.dat”

Unit usage                              Ami_per_unit

0-50                                         free

51-100                                     80 paisa

101-200                                   1.20 paisa

Above 200                              1.50 paisa

“Total amount will be calculated by (unit_usage*Amt_per_unit)

Import pickle

def write_data():

    Electricity=[]

    file=open('Electricity.dat','ab')

    kno=int(input('Enter K no. : ' ))

    consumer=input("Enter consumer name : ")

    unit_usage=int(input('Enter no. of used unit :'))

    amt_per_unit=int(input("Enter amount per unit : "))

    if unit_usage<=50:

            tot_amt=0

    elif unit_usage<=100:

        amt_per_unit=0.80

    elif unit_usage<=200:

        amt_per_unit=1.20

    else:

        amt_per_unit=1.50

    tot_amt=unit_usage*amt_per_unit

    Electricity=[kno, consumer, unit_usage, amt_per_unit, tot_amt]

    pickle.dump(Electricity,file)

file.close()

Q11. Observe the following declaration carefully:

Electricity=[kno, consumer, unit_usage, amt_per_unit, bill_amt]

Write a function to read a file electricity.dat and print the bill on screen of all customers whose bill amount is more than ₹ 1000 present in a file.

def read_data():

    file=open('Electricity.dat','rb')

    try:

        while True:

            record=pickle.load(file)

            if record[4]>1000:

                print(record)

      except EOFError:

            pass

    file.close()

 

Q12. (a) A binary file "Bank.dat" has structure AccNo, AccHolder, Acc Type, Bal. Write a user defined function add_rec() to accept all details of customer and append the data into a file "Bank.dat".

import pickle

def add_rec():

    file=open("Bank.dat", 'ab')

    bankRec=[]

    while  True:

            AccNo=int(input("Enter Account No. : "))

            AccHolder=input("Enter Name of Account Holder :")

            AccType=input("Enter Account Type (S-Saving, C-Current) :")

            Bal=int(input("Enter BalanaceRs. :"))

            data=[AccNo, AccHolder, Acc Type, Bal]

            bankRec.append(data)

            ch=input("Do you want to add more record : (Y/N) :").upper()

            if ch=='N':  break

    pickle.dump(bankRec,file)

    file.close()

(b) Write a function CountAccType() in Python to count and return number of accounts of type ‘Saving’ form a binary file “Bank.dat”.

Note: Check the account type, it must be "S" or "s".

def CountAccType():

    file=open("Bank.dat", 'rb')

    try:

        count=0

        while True:

            record=pickle.load(file)

                if record[2] is 'Ss':

                        count=count+1

    exceptEOFError:

            pass

    file.close()

    return count       

Q14. Define a function write_data() in binary mode to create a file "stud.data". Input rollno, name, and marks in three subjects Physics, Chemistry and Maths. Calculate the percentage of each student. Record the data into the file.

Structure of file: "Stud.dat” must be [roll_no, Name, M_Physics, M_ChemistryM_Maths, Per]

import pickle as p

def write_data():

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

    record=[]

    roll_no=int(input("Enter Roll No. "))

    Name=input("Enter Name :")

    M_Physics=int(input("Enter Physics Marks "))

    M_Chemistry=int(input("Enter Chemistry Marks "))

    M_Maths=int(input("Enter Maths Marks "))

    Per=(M_Physics+M_Chemistry+M_Maths)/3

    data=[roll_no, Name, M_Physics,M_Chemistry, M_Maths, Per]

    record.append(data)

    p.dump(record,file)

    file.close()

Q15. Write a function calculate_percent() in binary mode to read a file "Stud.dat”. Calculate the percentage of each student for Physics, Chemistry and Maths. Assuming the file "Stud.dat" contains roll no. Name, M_Physics, M_Chemistry,M_Maths for 100 students and print the data including calculated percentage on screen.

import pickle as p

def read_data():

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

    try:

            while True:

                    data=p.load(file)

                    per=(data[2]+data[3]+data[4])/3

                    r=data[0]

                    nm=data[1]

                    m1=data[2]

                    m2=data[3]

                    m3=data[4]

                    print(r,nm,m1,m2,m3,per, sep='\t')

    except EOFError:

        pass

    file.close()

Q16. School manages 12thclass student's data in a binary file "Student.dat” withfollowing list:

Stud=[Roll_no, Name, Marks1, Marks2, Marks3]

Write a function display_result() to read the data/records from binary "Student.dat” and display all the records on the screen after calculating the average of three subjects.

import pickle as p

def display_result():

      file= open('Studet.dat','rb')

      while True:     

           try:

                        Stud=p.load(file)

                        Roll_no=Stud[0]

                        Name=Stud[1]

                        Marks1=Stud1[2]

                        Marks2=Stud1[3]

                        Marks3=Stud1[4]

                        avg=(Marks1+Marks2+Marks3)/3

                        print(Roll_no, Name, Marks1, Marks2, Marks3,avg, sep='\t')

           except Exception:

                 pass

      file.close()

 

Q17. Given a binary file PHONE DAT, containing records of the following dictionary:

Phonlist={'name':name,'address':address,'phone':phone}

Write a function TRANSFER() in Python that would copy all those records which are having Phone no starts with 8 from PHONE.DAT to PHONBACK.DAT

Note: Each phone no. is of ten digit long of type integer.

def search():

    file = open("PHONE DAT","rb")

    file1=open('PHONBACK.DAT', 'wb')

 

    while True:

        try:

            record = pickle.load(file)

            if int(record['phone'])//1000000000==9:

                print(record['phone'])

                rec=record

                print(rec)

                pickle.dump(record,file1)

        except EOFError:

            break      

    file.close()

    file1.close()

Q18. Consider a list Vehicle containing vehicle name of type string, sitting capacity of type integer

Write function copy_data() to copy all the records present in a binary “CARS.DAT” into another "TAXI.DAT". Also, count and return the no. of records copied into a file "TAXI.DAT”.

import pickle

def create_data():

      fr=open('CARS.DAT','rb')

      fw=open('TAXI.DAT','wb')

      count=0

      while True:

            try:

           

                  record=pickle.load(fr)

                  pickle.dump(record,fw)

                  count + =1

            except Exception:

                  break

          

      fr.close()

      fw.close()

     return count 

#main program               

create_data()

 

Q19. Write a function search_candiate() in Python to search a record by candidate id from a binary file. “candidate.dat”. If the record is not found then print the appropriate message. File contains the record of the following list:

Candidates=[C_id, C_Name, C_Percentage]

import pickle as p

def search_candidate():

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

    try:

        while True:

            rec=p.load(file)

            if rec[0]=cid:

                print(rec[0],rec[1],rec[2],sep='\t')

                break

            except EOFError:

                print("Record not found")

        file.close()

Q20.Define a function backup() in Python which reads the content of a binary file "Telephone.dat" and copies only those details from “Telephone.dat” to "Backup.dat” where area code is 11. Assume that the binary file contains the objects of the following Dictionary:

Tele={“PhoneNo": value, "C_name":value,"Areacode":value}

*Area code is of type integer.

def search():

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

    file1=open('Backup.dat', 'wb')

 

    while True:

        try:

            record = pickle.load(file)

            if int(record['phone'])==11:

                pickle.dump(record,file1)

        except EOFError:

            print(“File copied”)

    file.close()

    file1.close()

 

Q21. Define a function new_connections() in Python to accept a new data from user and append it into a file "NConn.dat", only those details where area code is 11. Assume that the binary file "NCon.dat" is an existing file with more than 500 records contains the objects as per the following Dictionary:

Tele={“PhoneNo": value, "C_name": value, "Areacode": value]

*Areacode is of type integer

def b=new_connections():

    file=open("NConn.dat",'ab')

    rec=[]

    pno=int(input("Enter phone no."))

    name=input("Enter name")

    ar_c=int(input("Enter Area code "))

    if ar_c==11:

        rec={"PhoneNo": pno,"C_Name":name,"Areacode":ar_c}

        pickle.load(rec,file)

    file.close()

   Menu Driven Program

Q 1. Write a menu driven program in Python that asks the user to add, display, and search records of students stored in a binary file. The student record contains roll no, name and test score. It should be stored in a dictionary object. Your program should pickle the object and save it to a binary file.

Program 

import pickle

def set_data():

    rollno = int(input('Enter roll number: '))

    name = input('Enter name: ')

    test_score = int(input('Enter test score: '))

    print()

   

    #create a dictionary

    student = {}

    student['rollno'] = rollno

    student['name'] = name

    student['test_score'] = test_score

   

    return student

 

def display_data(student):

    print('Roll number:', student['rollno'])

    print('Name:', student['name'])

    print('Test Score:', student['test_score'])

    print()

 

def write_record():

    #open file in binary mode for writing.

    outfile = open('student.dat', 'ab')

 

    #serialize the object and writing to file

    pickle.dump(set_data(), outfile)

 

    #close the file

    outfile.close()

 

def read_records():

    #open file in binary mode for reading

    infile = open('student.dat', 'rb')

 

    #read to the end of file.

    while True:

        try:

            #reading the oject from file

            student = pickle.load(infile)

 

            #display the object

            display_data(student)

        except EOFError:

            break

 

    #close the file

    infile.close()

 

def search_record():

    infile = open('student.dat', 'rb')

    rollno = int(input('Enter rollno to search: '))

    flag = False

   

    #read to the end of file.

    while True:

        try:

            #reading the oject from file

            student = pickle.load(infile)

 

            #display record if found and set flag

            if student['rollno'] == rollno:

                display_data(student)

                flag = True

                break

           

        except EOFError:

            break

 

    if flag == False:

        print('Record not Found')

        print()

       

    #close the file

    infile.close()

 

def show_choices():

    print('Menu')

    print('1. Add Record')

    print('2. Display Records')

    print('3. Search a Record')

    print('4. Exit')

 

def main():

    while(True):

        show_choices()

        choice = input('Enter choice(1-4): ')

        print()

       

        if choice == '1':

            write_record()

           

        elif choice == '2':

            read_records()

 

        elif choice == '3':

            search_record()

 

        elif choice == '4':

            break

       

        else:

            print('Invalid input')

           

#call the main function.

main()

Output

Menu

1. Add Record

2. Display Records

3. Search a Record

4. Exit

Enter choice(1-4): 1

 

Enter roll number: 21

Enter name: Jyotsna

Enter test score: 68

 

Menu

1. Add Record

2. Display Records

3. Search a Record

4. Exit

Enter choice(1-4): 1

 

Enter roll number: 22

Enter name: Satyam

Enter test score: 99

 

Menu

1. Add Record

2. Display Records

3. Search a Record

4. Exit

Enter choice(1-4): 2

 

Roll number: 21

Name: Jyotsna

Test Score: 78

 

Roll number: 22

Name: Satyam

Test Score: 99

 

Menu

1. Add Record

2. Display Records

3. Search a Record

4. Exit

Enter choice(1-4): 3

 

Enter rollno to search: 10

Record not Found

 

Menu

1. Add Record

2. Display Records

3. Search a Record

4. Exit

Enter choice(1-4): 3

 

Enter rollno to search: 22

Roll number: 22

Name: Satyam

Test Score: 99

 

Menu

1. Add Record

2. Display Records

3. Search a Record

4. Exit

Enter choice(1-4): 4

Q 2. Write a menu driven program in Python that asks the user to add, display, and search records of employee stored in a binary file. The employee record contains employee code, name and salary. It should be stored in a list object. Your program should pickle the object and save it to a binary file.

Program 

import pickle
def set_data():
    empcode = int(input('Enter Employee code: '))
    name = input('Enter Employee name: ')
    salary = int(input('Enter salary: '))
    print()
    
    #create a list
    employee = [empcode,name,salary]
    
    return employee
 
def display_data(employee):
    print('Employee code:', employee[0])
    print('Employee name:', employee[1])
    print('Salary:', employee[2])
    print()
 
def write_record():
    #open file in binary mode for writing.
    outfile = open('emp.dat', 'ab')
 
    #serialize the object and writing to file
    pickle.dump(set_data(), outfile)
 
    #close the file
    outfile.close()
 
def read_records():
    #open file in binary mode for reading
    infile = open('emp.dat', 'rb')
 
    #read to the end of file.
    while True:
        try:
            #reading the oject from file
            employee = pickle.load(infile)
 
            #display the object
            display_data(employee)
        except EOFError:
            break
 
    #close the file
    infile.close()
def search_record():
    infile = open('emp.dat', 'rb')
    empcode = int(input('Enter employee code to search: '))
    flag = False
    
    #read to the end of file.
    while True:
        try:
            #reading the oject from file
            employee = pickle.load(infile)
 
            #display record if found and set flag
            if employee[0] == empcode:
                display_data(employee)
                flag = True
                break
            
        except EOFError:
            break
 
    if flag == False:
        print('Record not Found')
        print()
        
    #close the file
    infile.close()
 
def show_choices():
    print('Menu')
    print('1. Add Record')
    print('2. Display Records')
    print('3. Search a Record')
    print('4. Exit')
 
def main():
    while(True):
        show_choices()
        choice = input('Enter choice(1-4): ')
        print()
        
        if choice == '1':
            write_record()
            
        elif choice == '2':
            read_records()
 
        elif choice == '3':
            search_record()
 
        elif choice == '4':
            break
        
        else:
            print('Invalid input')
            
#call the main function.
main()

Output

Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 1
 
Enter Employee code: 100
Enter Employee name: Manjulika
Enter salary: 23000
 
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 1
 
Enter Employee code: 101
Enter Employee name: Jyotsna
Enter salary: 98000
 
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 2
 
Employee code: 100
Employee name: Manjulika
Salary: 23000
 
Employee code: 101
Employee name: Jyotsna
Salary: 98000
 
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 3
 
Enter employee code to search: 101
Employee code: 101
Employee name: Jyotsna
Salary: 98000
 
Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 4

 

No comments:

Post a Comment