Binary file operations with pickle Theory — Lecture 32
CBSE | XII CS | Computational Thinking and Programming – 2 | 35 min
You are an expert CBSE XII CS Computer Science teacher, examiner, and study material creator. =========================================== SCOPE — READ BEFORE GENERATING ANYTHING =========================================== Today's lecture covers ONE topic only: "Binary file operations with pickle" Lecture number 32 of 91 | Duration: 35 minutes | Board: CBSE Chapter: Computational Thinking and Programming – 2 HARD RULE: Every piece of content you generate — notes, examples, questions, tips — must be directly relevant to "Binary file operations with pickle" only. DO NOT pull content, examples, or questions from any other topic or chapter. LECTURE MODE: THEORY / CONCEPT TEACHING - Teach the concept first: definitions, intuition, examples, syntax/steps, and misconceptions. - Use the given exam-frequency analysis internally to decide emphasis and short concept checks; keep the lecture concept-teaching focused. - Keep content tightly scoped to today's concept list. =========================================== SECTION 1: LECTURE INFORMATION =========================================== Class: XII CS | Subject: Computer Science | Board: CBSE Topic: Binary file operations with pickle Theory Subtopics to cover today: - Binary file operations with pickle Student level: Class XII, CBSE Board, average to above-average students preparing for board exams =========================================== SECTION 2: TEACHER'S REFERENCE NOTES =========================================== Binary file operations with pickle Theory Concept ID: U1_BINARY_PICKLE_OPS. Primary Sub-subtopic: Binary file operations with pickle. Question-bank grouping: File Handling. Use this lecture for theory, examples, misconceptions, and short concept checks mapped to this concept ID. Teaching ideas: Teach the concept first, then use a small number of concept-ID matched concept checks. =========================================== SECTION 3: EXAM FREQUENCY DATA (Year-wise) =========================================== Teaching priority: HIGH High-yield concepts: Binary file operations with pickle, CSV file read write and search, Binary file operations with pickle, File basics paths modes seek and tell, Binary file operations with pickle | Year | Questions | Marks | |------|-----------|-------| | 2021 | 6 | 6 | | 2022 | 2 | 9 | | 2023 | 6 | 26 | | 2024 | 4 | 19 | | 2025 | 3 | 11 | | 2026 | 2 | 6 | | **Total** | **23** | **77** | =========================================== SECTION 4: EXAM ANALYSIS INPUT — DO NOT PRINT THESE IN THEORY NOTES (Scope: "Binary file operations with pickle" only — 23 questions from board papers) =========================================== THEORY LECTURE RULE: use these PYQs only as private analysis data — this lecture is PURELY THEORY. - Cover every concept and trap revealed by these PYQs in the study notes - Do NOT print, quote, reproduce, paraphrase, or label any actual PYQ in the final HTML - Self-generate your own tricky/important questions and examples about the concept itself only — do not call them "PYQ-pattern", "PYQ-style", "board-style", or reference PYQs/previous years at all - In theory lectures, generated questions must be MCQ or Short Answer only - Never use the word "PYQ" or phrases like "previous year question" anywhere in the visible HTML --- 2021 Board Exam (6 questions | 6 marks) --- Q1. [MCQ] [1M] [Easy] Section-A Which of the following statement is incorrect in the context of binary files? a) Information is stored in the same format in which the information is held in memory. b) No character translation takes place. c) Every line ends with a new line character. d) pickle module is used for reading and writing. Q2. [MCQ] [1M] [Easy] Section-A Which of the following statement is true? a) pickling creates an object from a sequence of bytes b) pickling is used for object serialization c) pickling is used for object deserialization d) pickling is used to manage all types of files in Python Q3. [MCQ] [1M] [Easy] Section-A Which of the following statement opens a binary file record.bin in write mode and writes data from a list lst1 = [1,2,3,4] on the binary file? a) with open('record.bin','wb') as myfile: pickle.dump(lst1,myfile) b) with open('record.bin','wb') as myfile: pickle.dump(myfile,lst1) c) with open('record.bin','wb+') as myfile: pickle.dump(myfile,lst1) d) with open('record.bin','ab') as myfile: pickle.dump(myfile,lst1) Q4. [MCQ] [1M] [Easy] Section-B Raghav is trying to write a tuple tup1 = (1,2,3,4,5) on a binary file test.bin. Consider the following code written by him. import pickle tup1 = (1,2,3,4,5) myfile = open("test.bin",'wb') pickle._______ #Statement 1 myfile.close() Identify the missing code in Statement 1. a) dump(myfile,tup1) b) dump(tup1, myfile) c) write(tup1,myfile) d) load(myfile,tup1) Q5. [MCQ] [1M] [Easy] Section-B A binary file employee.dat has the following data: | Empno | Empname | Salary | |-------|---------------|--------| | 101 | Anuj | 50000 | | 102 | Arijita | 40000 | | 103 | Hanika | 30000 | | 104 | Firoz | 60000 | | 105 | Vijaylakshmi | 40000 | def display(eno): f=open("employee.dat","rb") totSum=0 try: while True: R=pickle.load(f) if R[0]==eno: __________ #Line1 totSum=totSum+R[2] except: f.close() print(totSum) When the above mentioned function display(103) is executed, the output displayed is 190000. Write appropriate jump statement from the following to obtain the above output. a) jump b) break c) continue d) return Q6. [MCQ] [1M] [Easy] Section-C Choose the function name that should be used in the blank space of line marked as Statement-6 to create the desired CSV File. (Refer to the CSV file creation code in the case study: stuwriter._____(data)) a) dump() b) load() c) writerows() d) writerow() --- 2022 Board Exam (2 questions | 9 marks) --- Q1. [Programming] [4M] [Medium] Section-E Aman is a Python programmer. He has written a code and created a binary file record.dat with employeeid, ename and salary. The file contains 10 records. He now has to update a record based on the employee id entered by the user and update the salary. The updated record is then to be written in the file temp.dat. The records which are not to be updated also have to be written to the file temp.dat. If the employee id is not found, an appropriate message should be displayed. import _______ #Statement 1 def update_data(): rec={} fin=open("record.dat","rb") fout=open("_____________") #Statement 2 found=False eid=int(input("Enter employee id to update their salary :: ")) while True: try: rec=______________ #Statement 3 if rec["Employee id"]==eid: found=True rec["Salary"]=int(input("Enter new salary :: ")) pickle.____________ #Statement 4 else: pickle.dump(rec,fout) except: break if found==True: print("The salary of employee id ",eid," has been updated.") else: print("No employee with such id is not found") fin.close() fout.close() (i) Which module should be imported in the program? (Statement 1) (ii) Write the correct statement required to open a temporary file named temp.dat. (Statement 2) (iii) Which statement should Aman fill in Statement 3 to read the data from the binary file, record.dat and in Statement 4 to write the updated data in the file, temp.dat? Q2. [Programming] [5M] [Hard] Section-D Give any one point of difference between a binary file and a csv file. Write a Program in Python that defines and calls the following user defined functions: (i) add() – To accept and add data of an employee to a CSV file 'furdata.csv'. Each record consists of a list with field elements as fid, fname and fprice to store furniture id, furniture name and furniture price respectively. (ii) search() – To display the records of the furniture whose price is more than 10000. --- 2023 Board Exam (6 questions | 26 marks) --- Q1. [Programming] [4M] [Medium] Section-E Shreyas is a programmer, who has recently been given a task to write a user defined function named write_bin() to create a binary file called Cust_file.dat containing customer information — customer number (c_no), name (c_name), quantity (qty), price (price) and amount (amt) of each customer. The function accepts customer number, name, quantity and price. Thereafter, it displays the message 'Quantity less than 10..... Cannot SAVE', if quantity entered is less than 10. Otherwise the function calculates amount as price * quantity and then writes the record in the form of a list into the binary file. import pickle def write_bin(): bin_file= ______ #Statement 1 while True: c_no=int(input("enter customer number")) c_name=input("enter customer name") qty=int(input("enter qty")) price=int(input("enter price")) if ______: #Statement 2 print ("Quantity less than 10..Cannot SAVE") else: amt=price * qty c_detail=[c_no, c_name, qty, price, amt] ______ #Statement 3 ans=input("Do you wish to enter more records y/n") if ans.lower()=='n': ______ #Statement 4 ______ #Statement 5 ______ #Statement 6 (i) Write the correct statement to open a file 'Cust_file.dat' for writing the data of the customer. (ii) Which statement should Shreyas fill in Statement 2 to check whether quantity is less than 10. (iii) Which statement should Shreyas fill in Statement 3 to write data to the binary file and in Statement 4 to stop further processing if the user does not wish to enter more records. Q2. [Programming] [4M] [Medium] Section-E Shreyas is a programmer, who has recently been given a task to write a user defined function named write_bin() to create a binary file called Cust_file.dat containing customer information — customer number (c_no), name (c_name), quantity (qty), price (price) and amount (amt) of each customer. The function accepts customer number, name, quantity and price. Thereafter, it displays the message 'Quantity less than 10..... Cannot SAVE', if quantity entered is less than 10. Otherwise the function calculates amount as price * quantity and then writes the record in the form of a list into the binary file. import pickle def write_bin(): bin_file= ______ #Statement 1 while True: c_no=int(input("enter customer number")) c_name=input("enter customer name") qty=int(input("enter qty")) price=int(input("enter price")) if ______: #Statement 2 print ("Quantity less than 10..Cannot SAVE") else: amt=price * qty c_detail=[c_no, c_name, qty, price, amt] ______ #Statement 3 ans=input("Do you wish to enter more records y/n") if ans.lower()=='n': ______ #Statement 4 ______ #Statement 5 ______ #Statement 6 (i) Write the correct statement to open a file 'Cust_file.dat' for writing the data of the customer. (ii) Which statement should Shreyas fill in Statement 2 to check whether quantity is less than 10. (Option for part (iii) only) (iii) What should Shreyas fill in Statement 5 to close the binary file named Cust_file.dat and in Statement 6 to call a function to write data in binary file ? Q3. [Programming] [4M] [Medium] Section-E Atharva is a programmer, who has recently been given a task to write a Python code to perform the following binary file operation with the help of a user defined function/module : - Copy_new() : to create a binary file new_items.dat and write all the item details stored in the binary file, items.dat, except for the item whose item_id is 101. The data is stored in the following format : {item_id:[item_name,amount]} import ______ # Statement 1 def Copy_new(): f1= ______ # Statement 2 f2= ______ # Statement 3 item_id=int(input("Enter the item id")) item_detail= ______ # Statement 4 for key in item_detail: if ______: # Statement 5 pickle. ______ # Statement 6 f1.close() f2.close() He has succeeded in writing partial code and has missed out certain statements. Therefore, as a Python expert, help him to complete the code based on the given requirements : (i) Which module should be imported in the program ? (Statement 1) (ii) Write the correct statement required to open the binary file "items.dat". (Statement 2) (iii) Which statement should Atharva fill in Statement 3 to open the binary file "new_items.dat" and in Statement 4 to read all the details from the binary file "items.dat". Q4. [Programming] [4M] [Medium] Section-E Atharva is a programmer, who has recently been given a task to write a Python code to perform the following binary file operation with the help of a user defined function/module : - Copy_new() : to create a binary file new_items.dat and write all the item details stored in the binary file, items.dat, except for the item whose item_id is 101. The data is stored in the following format : {item_id:[item_name,amount]} import ______ # Statement 1 def Copy_new(): f1= ______ # Statement 2 f2= ______ # Statement 3 item_id=int(input("Enter the item id")) item_detail= ______ # Statement 4 for key in item_detail: if ______: # Statement 5 pickle. ______ # Statement 6 f1.close() f2.close() He has succeeded in writing partial code and has missed out certain statements. Therefore, as a Python expert, help him to complete the code based on the given requirements : (i) Which module should be imported in the program ? (Statement 1) (ii) Write the correct statement required to open the binary file "items.dat". (Statement 2) (Option for part iii only) (iii) What should Atharva write in Statement 5 to apply the given condition and in Statement 6 to write data in the binary file "new_items.dat". Q5. [Programming] [5M] [Hard] Section-E (i) Differentiate between r+ and w+ file modes in Python. (ii) Consider a file, SPORT.DAT, containing records of the following structure: [SportName, TeamName, No_Players] Write a function, copyData(), that reads contents from the file SPORT.DAT and copies the records with Sport name as "Basket Ball" to the file named BASKET.DAT. The function should return the total number of records copied to the file BASKET.DAT. (ii) A Binary file, CINEMA.DAT has the following structure: {MNO:[MNAME, MTYPE]} Where MNO – Movie Number, MNAME – Movie Name, MTYPE is Movie Type. Write a user defined function, findType(mtype), that accepts mtype as parameter and displays all the records from the binary file CINEMA.DAT, that have the value of Movie Type as mtype. Q6. [Programming] [5M] [Hard] Section-E (i) How are text files different from binary files? (ii) A Binary file, CINEMA.DAT has the following structure: {MNO:[MNAME, MTYPE]} Where MNO – Movie Number, MNAME – Movie Name, MTYPE is Movie Type. Write a user defined function, findType(mtype), that accepts mtype as parameter and displays all the records from the binary file CINEMA.DAT, that have the value of Movie Type as mtype. --- 2024 Board Exam (4 questions | 19 marks) --- Q1. [Programming] [4M] [Medium] Section-E Write a program in Python to create a binary file Employee.dat and write the following data into it: Employee ID, Employee Name, Department, Salary Q2. [Programming] [5M] [Hard] Section-E (a) (i) What is the main purpose of seek() and tell() method ? (ii) Consider a binary file, Cinema.dat containing information in the following structure : [Mno, Mname, Mtype] Write a function, search_copy(), that reads the content from the file Cinema.dat and copies all the details of the "Comedy" movie type to file named movie.dat. (ii) A Binary file, "Items.dat" has the following structure : [Icode, Description, Price] Where Icode – Item code Description – Detail of item Price – Price of item Write a function Add_data(), that takes Icode, Description and Price from the user and writes the information in the binary file "Items.dat". Q3. [Programming] [5M] [Hard] Section-E (b) (i) Give one difference between write() and writeline() function in text file. (ii) A Binary file, "Items.dat" has the following structure : [Icode, Description, Price] Where Icode – Item code Description – Detail of item Price – Price of item Write a function Add_data(), that takes Icode, Description and Price from the user and writes the information in the binary file "Items.dat". Q4. [Programming] [5M] [Hard] Section-E Surya is a manager working in a recruitment agency. He needs to manage the records of various candidates. For this, he wants the following information of each candidate to be stored: - Candidate_ID – integer - Candidate_Name – string - Designation – string - Experience – float You, as a programmer of the company, have been assigned to do this job for Surya. (I) Write a function to input the data of a candidate and append it in a binary file. (II) Write a function to update the data of candidates whose experience is more than 10 years and change their designation to "Senior Manager". (III) Write a function to read the data from the binary file and display the data of all those candidates who are not "Senior Manager". --- 2025 Board Exam (3 questions | 11 marks) --- Q1. [Assertion-Reason] [1M] [Easy] Section-A Assertion (A): For a binary file opened using 'rb' mode, the pickle.dump() method will display an error. Reason (R): The pickle.dump() method is used to read from a binary file. (A) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation for Assertion (A). (B) Both Assertion (A) and Reason (R) are true and Reason (R) is not the correct explanation for Assertion (A). (C) Assertion (A) is true but Reason (R) is false. (D) Assertion (A) is false but Reason (R) is true. Q2. [Programming] [5M] [Hard] Section-E Keshav is the IT Head in a hospital. He needs to manage the records of all the doctors in the hospital. For this, he wants to store the following information of each doctor in a file : D_ID – An integer to store Doctor ID. D_Name – A string to store doctor's name. D_Dept – A string to store the Department of the doctor. (Surgery, Radiology, etc.) Experience – An integer to store doctor's experience (in years) For example, a doctor's information may be : [1256, 'R. Gupta', 'Cardiology', 15] As an applicant for the post of a Programmer, you have to answer the following questions in this context : (I) Write one difference of storing this data in a binary file over a CSV file. (II) Assume that the data is stored in a binary file, named DOCTORS.DAT, and each record is stored as a list. Write a function, in Python, to read and display all the records from the file DOCTORS.DAT. (III) Write a function addDoctor(), in Python, which accepts a doctor's data from the user and writes it in the file DOCTORS.DAT. Q3. [Programming] [5M] [Hard] Section-E Mr. Ravi, a manager at a tech company, needs to maintain records of employees. Each record should include: Employee_ID, Employee_Name, Department and Salary. Write the Python functions to: I. Input employee data and append it to a binary file. (2 marks) II. Update the salary of employees in the "IT" department to 200000. (3 marks) --- 2026 Board Exam (2 questions | 6 marks) --- Q1. [MCQ] [1M] [Easy] Section-A Consider the statement given below : f1 = open("pqr.dat","_______") Which of the following is the correct file mode to open the file in read only mode ? (A) a (B) rb (C) r+ (D) rb+ Q2. [Programming] [5M] [Hard] Section-E NextStep is an organization which has a pool of resource persons to conduct training workshops on various topics related to ICT. The data of all its Resource Persons is stored in a binary file RESOURCES.DAT using the following record structure (each record is a tuple) : (R_ID, R_Name, R_Expertise, Charges) where : · R_ID – Resource Person's ID (An integer) · R_Name – Resource Person's Name (A string) · R_Expertise – Area of expertise of the Resource Person · Charges – Charges (in rupees) per hour to conduct a workshop For example, a record in the file is : (12, 'P. Velusami', 'Machine Learning', 5000) In this context, write the following user defined functions in Python : (i) Append() – To input the data of a Resource Person and write it in the file RESOURCES.DAT. (ii) Update() – To increase the Charges of each resource person by 500. =========================================== =========================================== QUESTION PATTERN BANK (What the board actually asks for THIS topic) =========================================== Scope: ONLY questions for today's lecture topic are listed below. DO NOT import questions from other topics or chapters. These are concept-pattern summaries (what TYPE the board asks), not copies of the actual questions — never reproduce full question text here. ### Concept: Binary file operations with pickle Pattern: MCQ=4, Programming=11 | Marks: 1M=4, 4M=6, 5M=5 | Total: 15 questions [MCQ] [1M] [Easy] × 3 → Core concept of Binary file operations with pickle [MCQ] [1M] [Easy] → Output tracing of an exception-handling snippet [Programming] [4M] [Medium] × 6 → Core concept of Binary file operations with pickle [Programming] [5M] [Hard] × 5 → Core concept of Binary file operations with pickle ### Concept: CSV file read write and search, Binary file operations with pickle Pattern: MCQ=1, Programming=2 | Marks: 1M=1, 5M=2 | Total: 3 questions [MCQ] [1M] [Easy] → Core concept of CSV file read write and search, Binary file operations with pickle [Programming] [5M] [Hard] × 2 → Core concept of CSV file read write and search, Binary file operations with pickle ### Concept: File basics paths modes seek and tell, Binary file operations with pickle Pattern: Assertion-Reason=1, MCQ=2, Programming=2 | Marks: 1M=3, 5M=2 | Total: 5 questions [MCQ] [1M] [Easy] × 2 → Core concept of File basics paths modes seek and tell, Binary file operations with pickle [Programming] [5M] [Hard] × 2 → Core concept of File basics paths modes seek and tell, Binary file operations with pickle [Assertion-Reason] [1M] [Easy] → Core concept of File basics paths modes seek and tell, Binary file operations with pickle =========================================== =========================================== IMPORTANCE ANALYSIS (allocate teaching time by this ranking) =========================================== | Rank | Concept | Score | Times Tested | Total Marks | Recent Years | Priority | |------|---------|-------|-------------|-------------|--------------|----------| | 1 | Binary file operations with pickle | 135 | 15 | 53M | 2026, 2025, 2024 | CRITICAL | | 2 | File basics paths modes seek and tell, Binary file operations with pickle | 45 | 5 | 13M | 2026, 2025, 2024 | CRITICAL | | 3 | CSV file read write and search, Binary file operations with pickle | 30 | 3 | 11M | 2025, 2022, 2021 | CRITICAL | CRITICAL concepts → full sub-section + comparison table + 2 worked examples HIGH concepts → 1 sub-section + 1 worked example MEDIUM concepts → definition + 1 quick example only =========================================== EXAMINER FINGERPRINT — TRAPS TO COVER INTERNALLY =========================================== Use the exam-frequency input only for internal analysis. Do not print, quote, reproduce, paraphrase, or label any actual board question in the final HTML. For this lecture, the generated teaching material must strongly cover these traps: No static trap list exists yet for "Binary file operations with pickle". Self-generate 4–7 traps from: - actual question patterns for Binary file operations with pickle, CSV file read write and search, Binary file operations with pickle, File basics paths modes seek and tell, Binary file operations with pickle - common wrong assumptions students make about this concept - output-tracing traps - syntax-vs-runtime traps - comparison traps - order/sequence traps Important: this list should be treated as dynamic — for lectures with no static trap list, generate traps yourself from the categories above rather than leaving this section thin. =========================================== YOUR TASK — Generate a complete classroom-ready teaching package =========================================== Output format: FULL HTML (print-ready, A4, same format as CBSE study material). Use the CSS classes below. NO plain Markdown — use HTML elements only. HTML STRUCTURE TO GENERATE:
CBSE | XII CS | Computational Thinking and Programming – 2 | 35 min