---
title: "Binary File Handling Class 12: Pickle and CSV Programs"
description: "Binary file handling class 12 and CSV files for CBSE 083: pickle modes tested, search, append and update programs, 4 and 5-mark answers with step marks."
canonical: https://learn.modernagecoders.com/cbse-class-12-computer-science-csv-and-binary-files
source: src/pages/cbse-class-12-computer-science-csv-and-binary-files.html
---
> Binary file handling class 12 and CSV files for CBSE 083: pickle modes tested, search, append and update programs, 4 and 5-mark answers with step marks.

Start here

## Where pickle and CSV fit in a longer course

The first course is the board syllabus itself. The second strengthens ordinary Python. The third follows the records into a database, which is where the project usually goes.

[![Computer Science Class 11 and 12 course thumbnail](/images/ip-cs-class-11-12.webp)  XI and XII / Board course Computer Science 11 and 12 File handling, the stack and Python to MySQL connectivity are its Class 12 core, with the report file and project running beside them. Open the course →](/courses/cbse-icse-computer-science-class-11-12-python-java-complete-course)[![Python for Teens course thumbnail](/images/python-teens.webp)  Python / Data in files Python for Teens Covers CSV writing, saved data and errors in practice, then puts them to work in projects that keep their records between runs. Open the course →](/courses/python-complete-masterclass-teens)[![MySQL for Teens course thumbnail](/images/mysql-teens.webp)  MySQL / Records at scale MySQL for Teens Search, update and append become SELECT, UPDATE and INSERT. A good second step once the file versions make sense. Open the course →](/courses/mysql-mastery-for-teens)

Ans. The short version

Binary file handling in Class 12 Computer Science (CBSE 083) uses the pickle module: dump() writes a Python object to a file opened in wb or ab, and load() reads one object back from a file opened in rb, until EOFError marks the end. The syllabus asks for read, write, search, append and update. CSV files use csv.writer() and csv.reader(). In the 2026-27 sample paper the two carry nine marks in Questions 33 and 36. Modern Age Coders teaches both live, personalised one to one at your own timing, and a priority demo comes first if you wish.

Q1. Three file types, one decision

## What is a binary file in Class 12, and how does it differ from text and CSV?

A binary file stores data as bytes in the form Python keeps it, so a list comes back as a list. A text file stores characters, and a CSV file is a text file whose lines are rows with values separated by commas.

| Point | Text file | Binary file | CSV file |
| --- | --- | --- | --- |
| Module to import | none | `pickle` | `csv` |
| Writes with | `write(), writelines()` | `pickle.dump(object, file)` | `writerow(), writerows()` |
| Reads with | `read(), readline(), readlines()` | `pickle.load(file)` | `csv.reader(file)` |
| A mark of 88 comes back as | the string '88' | the integer 88 | the string '88' |
| The end shows itself as | an empty string | EOFError | the for loop simply stops |
| Opens readably in Notepad | yes | no | yes, and in a spreadsheet |

### The six binary modes, each tested on a file of one record

| Mode | load() straight away | dump() of a new record | File missing? |
| --- | --- | --- | --- |
| `rb` | returns the record | refused | FileNotFoundError |
| `rb+` | returns the record | replaces the bytes at the start | FileNotFoundError |
| `wb` | refused | only the new record remains | created |
| `wb+` | EOFError, it was just emptied | only the new record remains | created |
| `ab` | refused | added after the old record | created |
| `ab+` | EOFError, pointer is at the end | added after the old record | created |

Forget the b, and Python complains at once: dumping into a file opened in `w` gives `TypeError: write() argument must be str, not bytes`. Assertion and reason items like these two tables; the official Question 20 asks about `rb`.

Q2. How many loads does it take?

## Pickle module Class 12: dump(), load() and the loop that ends on EOFError

Each dump() writes one object and each load() reads one object. To read a file of unknown length, call load() inside an endless loop and let EOFError end it.

***Create**one dump per record*

```
import pickle

def create_file():
    """Store each bus pass with its own dump."""
    passes = [[101, "Zoya", "R5", 3],
              [102, "Imran", "R2", 1],
              [103, "Leela", "R5", 6]]
    with open("pass.dat", "wb") as f:
        for record in passes:
            pickle.dump(record, f)
    print(len(passes), "records written")

create_file()
```

***Output**on our machine*

```
3 records written
```

A record here is pass number, name, route and months left.

***Read all**the loop to learn by heart*

```
import pickle

def show_all():
    """Display every record in pass.dat."""
    with open("pass.dat", "rb") as f:
        try:
            while True:
                record = pickle.load(f)
                print(record)
        except EOFError:
            print("No more records")

show_all()
```

***Output**on our machine*

```
[101, 'Zoya', 'R5', 3]
[102, 'Imran', 'R2', 1]
[103, 'Leela', 'R5', 6]
No more records
```

The `try` is outside the `while`, so the fourth load leaves the loop. With `try` inside and `pass` in the except, the loop would never stop.

### Two ways to store three records

|   | One dump per record | One dump of a list of records |
| --- | --- | --- |
| Write | `pickle.dump(record, f)` in a loop | `pickle.dump(passes, f)` once |
| Read | load() until EOFError | one load(), then loop over the list |
| Append | open in `ab` and dump | load the list, append to it, dump all in `wb` |
| Official answer, Question 36 | this way |   |

### Mixing them is the classic mistake

***Mixed shapes**runs, but misleads*

```
import pickle

with open("team.dat", "wb") as f:
    pickle.dump([["Asha", 4], ["Bela", 7]], f)
with open("team.dat", "ab") as f:
    pickle.dump(["Chand", 9], f)
with open("team.dat", "rb") as f:
    team = pickle.load(f)
print(len(team), team)
```

***Output**on our machine*

```
2 [['Asha', 4], ['Bela', 7]]
```

Chand is in the file, as a second object. One load never reaches him.

The exam usually tells you the shape of a record. If it does not say how records are stored, use one dump per record and write that in a comment. The flow of try and except is explained on [exception handling for Class 12](/cbse-class-12-computer-science-exception-handling).

Q3. Search, append, update

## Binary file programs Class 12: one loop, a different line inside

Search reads until the record matches. Append opens in ab and dumps. Update reads every record into a list, changes the ones that match and writes the whole list back.

***Search**with a flag*

```
import pickle

def find_pass(number):
    """Display the pass with this number."""
    found = False
    with open("pass.dat", "rb") as f:
        try:
            while not found:
                record = pickle.load(f)
                if record[0] == number:
                    print(record[1], "on route", record[2])
                    found = True
        except EOFError:
            print("Pass", number, "not found")

find_pass(103)
find_pass(110)
```

***Output**on our machine*

```
Leela on route R5
Pass 110 not found
```

A pass number is unique, so the loop stops at the first match. To find everyone on R5 you must read to the end.

***Append**ab mode*

```
import pickle

def add_pass():
    """Accept one record and add it at the end."""
    number = int(input("Pass number: "))
    name = input("Name: ")
    route = input("Route: ")
    months = int(input("Months: "))
    with open("pass.dat", "ab") as f:
        pickle.dump([number, name, route, months], f)
    print("Saved")

add_pass()
```

***Output**on our machine*

```
Pass number: 104
Name: Tenzin
Route: R2
Months: 2
Saved
```

Convert before dumping. If 104 is stored as a string, `find_pass(104)` will not find it.

***Update**read all, rewrite all*

```
import pickle

def extend_route(route, extra):
    """Add extra months to every pass on a route."""
    records = []
    changed = 0
    with open("pass.dat", "rb") as f:
        try:
            while True:
                record = pickle.load(f)
                if record[2] == route:
                    record[3] += extra
                    changed += 1
                records.append(record)
        except EOFError:
            pass
    with open("pass.dat", "wb") as f:
        for record in records:
            pickle.dump(record, f)
    return changed

print("Passes changed:", extend_route("R5", 2))
```

***Output**on our machine*

```
Passes changed: 2
```

| Load | Record | Route R5? | Goes into records as |
| --- | --- | --- | --- |
| 1 | 101 Zoya | yes | [101, Zoya, R5, 5] |
| 2 | 102 Imran | no | unchanged |
| 3 | 103 Leela | yes | [103, Leela, R5, 8] |
| 4 | 104 Tenzin | no | unchanged |
| 5 | none | EOFError | loop ends, file rewritten |

**The indent that matters:** `records.append(record)` lines up with the `if`, not inside it. One level deeper and Imran and Tenzin vanish from the file, with no error to warn you.

***Update in place**rb+, tell and seek*

```
import pickle

def change_route(number, new_route):
    """Overwrite one record of the same length."""
    with open("pass.dat", "rb+") as f:
        try:
            while True:
                position = f.tell()     # before the load
                record = pickle.load(f)
                if record[0] == number:
                    record[2] = new_route
                    f.seek(position)
                    pickle.dump(record, f)
                    print("Route changed")
                    break
        except EOFError:
            print("Not found")

change_route(102, "R7")
```

***Output**on our machine*

```
Route changed
```

### When is the in-place version safe?

Only when the new record takes exactly as many bytes as the old one. R2 and R7 are both two letters, so it worked.

We then tried it with a name made longer, Zoya to Zoya Khan. The new record ran into the next one, and the following load failed with `UnpicklingError`. With a shorter name, the leftover bytes broke it in the same way.

So in the exam, choose the rewrite. It is the method in the official answer to Question 36, and it has no length condition to forget.

### What about delete?

The 083 list for binary files is read, write, search, append and update. Deleting is not named. If a teacher asks, it is the update program with one change: append the record to the list only when it should stay.

Functions that return a count, as ours do, are covered in [functions for Class 12](/cbse-class-12-computer-science-functions).

Q4. reader, writer and the strings between them

## CSV file Class 12 Computer Science: reading, writing and updating rows

Open the file, make a writer or reader object from it, and work with rows as lists. Every value you read is a string, whatever it was when you wrote it.

***Write**header, then rows*

```
import csv

rows = [["Meenu", "Wheat", 40, 2400],
        ["Rao, Anita", "Cotton", 12, 7000],
        ["Harpal", "Wheat", 55, 2350]]

with open("harvest.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["Farmer", "Crop", "Quintals", "Rate"])
    writer.writerows(rows)

with open("harvest.csv", "r") as f:
    print(f.read())
```

***Output**on our machine*

```
Farmer,Crop,Quintals,Rate
Meenu,Wheat,40,2400
"Rao, Anita",Cotton,12,7000
Harpal,Wheat,55,2350
```

A value that contains a comma is wrapped in quotes by the writer, and the reader takes them off again.

***Read and total**skip the header, convert*

```
import csv

def crop_value(crop):
    """Return the total value of one crop."""
    total = 0
    with open("harvest.csv", "r", newline="") as f:
        reader = csv.reader(f)
        next(reader)                  # header row
        for row in reader:
            if row[1] == crop:
                total += int(row[2]) * int(row[3])
    return total

print("Wheat:", crop_value("Wheat"))
print("Jute:", crop_value("Jute"))
```

***Output**on our machine*

```
Wheat: 225250
Jute: 0
```

40 x 2400 is 96000 and 55 x 2350 is 129250. Leave out `next()` and nothing fails here, since no crop is called Crop, but a program that converts every row would stop with ValueError at "Quintals".

***Update**list in, list out*

```
import csv

def new_rate(crop, rate):
    """Change the rate of a crop in harvest.csv."""
    with open("harvest.csv", "r", newline="") as f:
        rows = list(csv.reader(f))
    changed = 0
    for row in rows[1:]:
        if row[1] == crop:
            row[3] = rate
            changed += 1
    with open("harvest.csv", "w", newline="") as f:
        csv.writer(f).writerows(rows)
    print(changed, "rows changed")

new_rate("Wheat", 2500)
with open("harvest.csv", "r") as f:
    print(f.read())
```

***Output**on our machine*

```
2 rows changed
Farmer,Crop,Quintals,Rate
Meenu,Wheat,40,2500
"Rao, Anita",Cotton,12,7000
Harpal,Wheat,55,2500
```

The slice `rows[1:]` skips the heading while changing, and `rows`, with the heading, is what gets written.

### What one wrong call writes

| Call | Result |
| --- | --- |
| `writerow([["p", 1], ["q", 2]])` | One row of two list texts. Use `writerows` |
| `writerows(["ab", "cd"])` | Rows `a,b` and `c,d` |
| `writerow(5)` | Error: iterable expected, not int |
| `writerow(["x", None, 2.5])` | `x,,2.5`, None becomes an empty value |
| `"9" > "85"` on values read back | True, because strings are compared letter by letter |

### Why newline="" is written in open()

The csv writer ends each row with its own line ending. On Windows, a file opened without `newline=""` adds a second one, and the reader then gives an empty list after every row:

***Blank rows**wrong on purpose*

```
[['a', '1'], [], ['b', '2'], []]
```

The first `row[1]` on an empty list raises IndexError. The official answer leaves it out and still earns its marks, so use it as protection in the lab.

Q5. Full answers with half marks

## Four and five-mark questions on CSV and binary files, solved

A four-mark CSV question has two functions of two marks each; the five-mark binary question has a two-mark append and a three-mark search or update. Try each on paper, then compare.

### Question A, CSV (4 marks)

A rescue zoo keeps Animals.csv with TagNo, Species and Weight, and no heading row. Write (I) `add_animal()` to accept one animal and append it; (II) `heavy(limit)` to display the tag and species of animals heavier than the limit, and return how many there are.

***Answer A**two functions*

```
import csv

def add_animal():
    """Append one animal typed by the user."""
    tag = input("Tag: ")
    species = input("Species: ")
    weight = float(input("Weight in kg: "))
    with open("Animals.csv", "a", newline="") as f:
        csv.writer(f).writerow([tag, species, weight])

def heavy(limit):
    """Show animals above limit kg, return the count."""
    count = 0
    with open("Animals.csv", "r", newline="") as f:
        for row in csv.reader(f):
            if float(row[2]) > limit:
                print(row[0], row[1])
                count += 1
    return count

for turn in range(3):
    add_animal()
print("Count:", heavy(90))
```

***Output**on our machine*

```
Tag: Z1
Species: Sloth bear
Weight in kg: 104.5
Tag: Z2
Species: Otter
Weight in kg: 9
Tag: Z3
Species: Leopard
Weight in kg: 92
Z1 Sloth bear
Z3 Leopard
Count: 2
```

Without float(), `row[2] > limit` would compare a string with a number and raise TypeError.

| Part | Half mark for each |
| --- | --- |
| I | input, append mode, writer object, writerow |
| II | read mode, reader object, condition with conversion, display and return |

### Question B, CSV (4 marks)

Fines.csv has the columns Member, Days, Paid (Y or N) and a heading row. Write (I) `copy_unpaid()` to copy the heading and the unpaid rows to Due.csv; (II) `due_total()` to return the money due in Due.csv at 2 rupees a day.

***Fines.csv**file, 4 lines*

```
Member,Days,Paid
Kiran,12,N
Sofia,5,Y
Arjun,8,N
```

***Answer B**two files open*

```
import csv

def copy_unpaid():
    """Copy heading and unpaid rows to Due.csv."""
    with open("Fines.csv", "r", newline="") as fin, \
         open("Due.csv", "w", newline="") as fout:
        writer = csv.writer(fout)
        for row in csv.reader(fin):
            if row[2] != "Y":
                writer.writerow(row)

def due_total():
    """Return the amount due at 2 a day."""
    days = 0
    with open("Due.csv", "r", newline="") as f:
        reader = csv.reader(f)
        next(reader)
        for row in reader:
            days += int(row[1])
    return days * 2

copy_unpaid()
print("Due:", due_total())
```

***Output**on our machine*

```
Due: 40
```

Testing for "not Y" lets the heading through without a separate line. Kiran 12 and Arjun 8 make 20 days.

### Question C, binary (2 + 3 marks)

A blood bank stores dictionaries with the keys donor, group and units in Blood.dat. Write functions to (I) input a record and append it; (II) display the donors of a given group and the total units, or a message if there are none.

***Answer C**dictionary records*

```
import pickle

def add_donor():
    """Append one donor record."""
    record = {}
    record["donor"] = input("Donor: ")
    record["group"] = input("Group: ")
    record["units"] = int(input("Units: "))
    with open("Blood.dat", "ab") as f:
        pickle.dump(record, f)

def group_total(group):
    """Display donors of a group and total units."""
    total = 0
    with open("Blood.dat", "rb") as f:
        try:
            while True:
                record = pickle.load(f)
                if record["group"] == group:
                    print(record["donor"])
                    total += record["units"]
        except EOFError:
            pass
    if total == 0:
        print("No donor of group", group)
    else:
        print("Units of", group, "=", total)

for turn in range(3):
    add_donor()
group_total("O+")
group_total("AB-")
```

***Output**on our machine*

```
Donor: Faiz
Group: O+
Units: 2
Donor: Nisha
Group: B+
Units: 1
Donor: Joel
Group: O+
Units: 1
Faiz
Joel
Units of O+ = 3
No donor of group AB-
```

| Part | Marks |
| --- | --- |
| I: header, append mode, input, dump() | ½ each |
| II: header | ½ |
| II: opening in rb | ½ |
| II: load() in a loop with try and except | 1 |
| II: condition and total | 1 |

### Question D, binary (2 + 3 marks)

Shows.dat holds lists of ShowID, Title, Seats and Price. Write functions to (I) write a list of shows to the file, one record at a time; (II) raise the Price by 10 percent for shows with fewer than 50 seats left, and display how many prices changed.

***Answer D**update by rewriting*

```
import pickle

def write_shows(shows):
    """Create Shows.dat, one dump per show."""
    with open("Shows.dat", "wb") as f:
        for show in shows:
            pickle.dump(show, f)

def raise_price():
    """Add 10 percent where seats are below 50."""
    kept = []
    changed = 0
    with open("Shows.dat", "rb") as f:
        try:
            while True:
                show = pickle.load(f)
                if show[2] < 50:
                    show[3] = show[3] * 110 // 100
                    changed += 1
                kept.append(show)
        except EOFError:
            pass
    write_shows(kept)
    print("Prices changed:", changed)

write_shows([["S1", "Ankuran", 35, 200],
             ["S2", "Tamasha", 80, 150],
             ["S3", "Rang", 12, 250]])
raise_price()
with open("Shows.dat", "rb") as f:
    for turn in range(3):
        print(pickle.load(f))
```

***Output**on our machine*

```
Prices changed: 2
['S1', 'Ankuran', 35, 220]
['S2', 'Tamasha', 80, 150]
['S3', 'Rang', 12, 275]
```

Part II reuses the function of part I to write the file back. Whole-number arithmetic keeps the price an integer.

Programs for the report file, with the roll number search and the marks update the syllabus lists, are in [the practical file guide](/blog/python-practical-file-class-12). To write one of these inside a three-hour paper, use [our 70-mark sample paper](/cbse-class-12-computer-science-sample-paper-2026-27).

Q6. Short questions

## CSV file in Python Class 12 questions, and short ones on pickle

These are the one and two-mark versions: modes, methods, types and one line that is wrong.

1. Which module and which two functions are used to store a dictionary in a binary file and read it back? Answer The pickle module; `dump()` stores it and `load()` reads it back.
2. Which is correct: `pickle.dump(f, rec)` or `pickle.dump(rec, f)`? Answer`pickle.dump(rec, f)`: the object first, then the file.
3. A program dumps 6 records separately. How many times does load() run, counting the one that fails? Answer Seven. The seventh finds nothing and raises EOFError.
4. Name the mode that lets you add records to a binary file without losing the old ones and also read. Answer`ab+`. Move the pointer with `seek(0)` before reading.
5. **Assertion:** Values read by csv.reader() must be converted before adding. **Reason:** csv.reader() returns each row as a list of strings. Answer Both are true, and the reason explains the assertion.
6. Differentiate between `writerow()` and `writerows()`. Answer writerow() takes one sequence and writes one row. writerows() takes a sequence of sequences and writes one row for each. `w.writerow([1, "Ana"])`; `w.writerows([[1, "Ana"], [2, "Bo"]])`.

1. Give two differences between a binary file and a CSV file. Answer A binary file holds bytes and needs pickle; a CSV file holds text and can be read in any editor. Values keep their type in a binary file and come back as strings from a CSV file.
2. How do you count the rows of a CSV file that has a heading? Answer`len(list(csv.reader(f))) - 1`, provided no blank rows were written.
3. What does `list(reader)` give when it is called a second time on the same reader? Answer An empty list. The first call used up the rows.
4. An update program runs without error and the file is now empty. What happened? Answer The file was opened in `wb` before it was read, or the records were never appended to the list. Read and close first, then write.
5. Find the error: `with open("a.dat", "r") as f: rec = pickle.load(f)`. Answer The mode must be `rb`. In text mode load() raises TypeError, since it needs bytes.
6. Why is a CSV file a good choice for data that will be opened in a spreadsheet? Answer It is plain text with one record per line and commas between values, and spreadsheet programs open it directly.

### The loop from memory

A class often opens with the eight-line reading loop on a blank page. When it comes without thinking, the long questions shrink.

### Test data that argues back

Programs are run with no match, two matches, an empty file and a name with a comma in it.

### Marked beside the scheme

Each part of your answer is ticked against the step it earns, and the missing step is written in by you.

If modes and pointers still feel uncertain, go back to [text file handling](/cbse-class-12-computer-science-file-handling). If they are clear, try the [case study questions](/cbse-class-12-computer-science-case-study-questions) and [the MCQ test](/cbse-class-12-computer-science-mcq-test).

One to one, at your own timing

## Pickle and CSV, taught to one student at a time

A five-mark program is learnt by writing it, having it corrected and writing it again. That needs a teacher who is looking at your page only, so the classes are personalised one to one and you decide the days and the clock time. A priority demo is the way to judge this first: you pay for one full class, and that fee is adjusted in month one if you enrol. Prefer a lighter look? Take the free demo class. Monthly billing, no admission fee, and any month end can be your last.

Before you enrol · Try a class

### Priority demo, at a slot you pick

a full live class of about 45 to 60 minutes

- One binary or CSV question attempted by you, start to finish
- Your own code run on data chosen to break it
- The step marks counted aloud, half by half
- Afterwards, a skill report in writing on modes, loops and conversion

[Book a priority demo](/book-demo)

The classes · Choose your own timing

### Personalised one to one

₹4,999

per month, 4 private classes, fully flexible timing

- Search, append and update practised on fresh records
- Report file programs checked as you write them
- Text files and exceptions revisited where the long answers need them
- The link to Python and MySQL when you are ready for it

Ask for a personalised plan

How long the chapter takes depends on how sure your loops and lists are. After the demo you get a plan in plain steps, not a fixed package. You see the monthly fee in your own currency on this page.

Studying outside India?

## Binary and CSV file classes for 083 students in other countries

If your CBSE school is in Bahrain, Nepal or Malaysia, Question 33 and Question 36 are waiting for you too. Tell us the hours your family keeps and the class goes there.

| Where you live | Time difference | Usual class window, local time | Format |
| --- | --- | --- | --- |
| India every Indian city | Indian time | Any time you choose | Personalised 1-on-1 |
| UAE and Oman Dubai, Abu Dhabi, Sharjah, Muscat | 1 h 30 min behind India | 3:00 PM to 9:00 PM | Personalised 1-on-1 |
| Saudi Arabia, Qatar, Kuwait, Bahrain Riyadh, Jeddah, Dammam, Doha, Kuwait City, Manama | 2 h 30 min behind India | 3:00 PM to 9:00 PM | Personalised 1-on-1 |
| Nepal Kathmandu | 15 min ahead of India | 4:30 PM to 9:00 PM | Personalised 1-on-1 |
| Ethiopia and East Africa Addis Ababa and East Africa Time | 2 h 30 min behind India | 4:30 PM to 9:00 PM | Personalised 1-on-1 |
| Singapore and Malaysia Singapore, Kuala Lumpur | 2 h 30 min ahead of India | 3:30 PM to 9:00 PM | Personalised 1-on-1 |

Python on your own computer is enough: pickle and csv come with it. If you use a school laptop that blocks installs, mention it when you book.

What families say

## Rated 4.9 across 547 Google reviews

Real reviews from real families. We neither write nor commission them.

★★★★★

"The one step solution for my son. Modern Age Coders make learning coding so simple that kids love it. The teachers explain complex concepts clearly with practical exercises and interactive content."

Ria Mukherjee

Parent

★★★★★

"Modern Age Coders has been a game-changer for me. I struggled to grasp IT concepts and coding before joining, but their classes transformed everything. I can now confidently write complex programs with ease."

Samriddha Mondal

Student

★★★★★

"One of the most wonderful education centres out there. Education is not limited to school syllabus but focuses on skill development."

Vansh Agarwal

Student

★★★★★

"My child Dhairya is really enjoying the Modern Age Coders classes. This is his first online class and he eagerly looks forward to it. I can already see his improvement, and the teachers are very cooperative."

Sonam Oswal

Parent of Dhairya

★★★★★

"Modern Age Coders have wonderful teachers who teach in a clear, easy and practical way. The teacher boosts students' confidence and inspires them to learn without hesitation."

Sonu Goyal

Parent

★★★★★

"I highly recommend this computer coding class! The teachers are incredibly knowledgeable and passionate about coding."

Ritu Kedia

Parent

The rest of the Class 12 series

## More pages for Class 12 students

Every page in the CBSE Class 12 Computer Science series, grouped by what you need.

### Practicals, project and viva

- [Class 12 CS viva questions](/cbse-class-12-computer-science-viva-questions)
- [Class 12 CS project with source code](/cbse-class-12-computer-science-project-python-mysql)
- [Class 12 CS project topics](/cbse-class-12-computer-science-project-topics)

### Exam, papers and marks

- [Class 12 CS sample paper practice](/cbse-class-12-computer-science-sample-paper-2026-27)
- [Class 12 CS exam date, pattern and marks](/cbse-class-12-computer-science-paper-pattern-and-marking-scheme)
- [Class 12 CS important questions](/cbse-class-12-computer-science-important-questions)

### Questions and practice

- [Class 12 CS MCQ test](/cbse-class-12-computer-science-mcq-test)
- [Class 12 CS output questions](/cbse-class-12-computer-science-output-questions)
- [Class 12 CS case study questions](/cbse-class-12-computer-science-case-study-questions)
- [Class 12 CS SQL questions](/cbse-class-12-computer-science-sql-queries)

### Chapter by chapter

- [Functions in Python Class 12](/cbse-class-12-computer-science-functions)
- [Exception handling Class 12](/cbse-class-12-computer-science-exception-handling)
- [Text file handling Class 12](/cbse-class-12-computer-science-file-handling)
- [Stack Class 12 Computer Science](/cbse-class-12-computer-science-stack)
- [Computer networks Class 12](/cbse-class-12-computer-science-computer-networks)
- [Python MySQL connectivity Class 12](/cbse-class-12-computer-science-python-mysql-connectivity)

### Notes, revision and help

- [Class 12 CS syllabus 2026-27](/cbse-class-12-computer-science-syllabus-2026-27)
- [Class 12 CS notes](/cbse-class-12-computer-science-notes)
- [Class 12 CS revision plan](/cbse-class-12-computer-science-revision-plan)
- [Class 12 CS crash course](/cbse-class-12-computer-science-crash-course)

**CBSE Class 12 Informatics Practices (065):** [Class 12 IP practical file](/cbse-class-12-informatics-practices-practical-file)  [Class 12 IP project with source code](/cbse-class-12-informatics-practices-project)  [Class 12 IP sample paper practice](/cbse-class-12-informatics-practices-sample-paper-2026-27)  [Class 12 IP important questions](/cbse-class-12-informatics-practices-important-questions)

**CBSE Class 12 Information Technology (802):** [IT 802 practical and project file](/cbse-class-12-it-802-practical-and-project-file)  [IT 802 Java notes and programs](/cbse-class-12-it-802-java-programs)  [IT 802 notes](/cbse-class-12-it-802-notes)

**CBSE Class 11 CS, IP and AI:** [Class 11 CS practical file](/cbse-class-11-computer-science-practical-file)  [Class 11 IP practical file](/cbse-class-11-informatics-practices-practical-file)  [CS or IP in Class 11](/computer-science-or-informatics-practices-class-11)

**ISC Computer Science (868):** [ISC Class 12 CS syllabus 2027](/isc-class-12-computer-science-syllabus-2027)  [ISC Class 12 CS practice paper](/isc-class-12-computer-science-specimen-paper-practice)  [ISC Class 12 practical questions solved](/isc-class-12-computer-science-practical-questions)  [ISC Boolean algebra and K-maps](/isc-class-12-computer-science-boolean-algebra)

**Program lists with output:** [Class 12 CS practical file](/blog/python-practical-file-class-12)  [20 Python programs for Class 12](/blog/python-programs-for-cbse-class-12)  [Menu-driven programs in Python](/blog/how-to-build-menu-driven-program-in-python)

Questions about binary and CSV files

## What students ask about binary and CSV files in Class 12

### What is binary file handling in Class 12 Computer Science?

It is storing Python objects such as lists and dictionaries as bytes, using the pickle module. The CBSE 083 syllabus for 2026-27 lists the modes rb, rb+, wb, wb+, ab and ab+, the dump() and load() methods, and the operations read, write, search, append and update.

### What is the pickle module in Class 12?

pickle is a Python module that turns an object into bytes and back. pickle.dump(obj, f) writes the object to a binary file that is open for writing, and pickle.load(f) returns the next object from a file open for reading. A list comes back as a list, with its numbers still numbers.

### Why do we use try and except EOFError with binary files?

Because load() has no other way to say that the file is over. It raises EOFError when nothing is left to read. Putting the reading loop inside try, with except EOFError, ends the loop cleanly. It also handles a file that is completely empty.

### How do you update a record in a binary file in Python?

Read every record into a list, change the records that match, close the file, then open it in wb and dump all the records again. The alternative is rb+ with tell() and seek(), but it is only safe when the changed record has the same length in bytes.

### How do you delete a record from a binary file?

Read all records, keep in a list only those that should stay, and write that list back in wb mode. Deleting is not named among the binary file operations of the 2026-27 syllabus, so treat it as extra practice on the update pattern.

### What is the difference between a CSV file and a text file?

A CSV file is a text file with a rule: each line is a record and the values are separated by commas. You read it with csv.reader(), which splits every line into a list of strings, and write it with csv.writer(), which adds commas and puts quotes around values that contain a comma.

### Why does my CSV file have a blank line after every row?

On Windows, the file was opened without newline="". The csv writer already ends each row, and text mode changes that ending again. Write open("data.csv", "w", newline=""), and the blank rows stop. Old files with blank rows can be read by skipping rows whose length is 0.

### How many marks are CSV and binary files in the board paper?

In the 2026-27 sample paper, Question 33 is a four-mark CSV program and Question 36 is a five-mark binary file program, with no internal choice in either. Question 20 adds one mark on the rb mode. CBSE does not promise the same split in the actual paper.

### Do I have to write import pickle and import csv in the answer?

The 2026-27 marking scheme says the import may be ignored in Questions 33 and 36 as part of the complete program. Write it anyway. It takes one line, and in the practical the program will not run without it.

### Should records be lists or dictionaries in a binary file?

Use what the question says. If it gives only field names, either will do; the official answer uses a list. A list is shorter to write, and you must remember which index holds what. A dictionary is longer but reads clearly: record["units"] needs no explanation.

### Can I get help with only the file handling chapter?

Yes. The classes are one to one and monthly, so the first weeks can be spent on files alone. Start with a priority demo, a full live class with a written skill report and its fee adjusted in the first month if you enrol, or with a free demo class.

Start

## Send us your hardest file question

Come to the free demo class with a binary or CSV question you could not finish. The teacher will not finish it for you: you get the next step, then the one after it, until it runs.

With a **priority demo** you fix the slot and have a full class: an append function, an update function, both tested and marked, and a skill report in writing to keep. If you go on to enrol, the demo fee is adjusted against your first month.

The whole paper is mapped on [exam date, pattern and marks](/cbse-class-12-computer-science-paper-pattern-and-marking-scheme).

[WhatsApp us](https://wa.me/919123366161?text=Hello%20Modern%20Age%20Coders.%20I%20want%20one%20to%20one%20help%20with%20binary%20and%20CSV%20files%20for%20CBSE%20Class%2012%20Computer%20Science%20083.) · [+91 91233 66161](tel:+919123366161) · [connect@modernagecoders.com](mailto:connect@modernagecoders.com)

Every class is live video. The form requests a callback and reserves nothing.

### Want it sooner? Book a priority demo

A full live class of about 45 to 60 minutes at a slot you pick, with a written skill report and learning roadmap on WhatsApp afterwards. The fee is adjusted against your first month if you enrol.

[Book a priority demo](/book-demo)

## Keep exploring Modern Age Coders

### By class and age

- [Number System Class 11 Computer Science: Conversions, Logic](/cbse-class-11-number-system-conversion)
- [Class 11 IP Sample Paper 2026-27 With Solution, 70 Marks](/cbse-class-11-informatics-practices-sample-paper)
- [Class 11 IP Notes 2026-27: All Four Units, With Code](/cbse-class-11-informatics-practices-notes)
- [Class 11 Computer Science Sample Paper 2026-27, Solved](/cbse-class-11-computer-science-sample-paper)
- [Class 11 Computer Science Project in Python, with Topics](/cbse-class-11-computer-science-project)
- [Class 11 Computer Science Notes 2026-27, Chapter Wise](/cbse-class-11-computer-science-notes)
- [Coding for Class 8: Python OOP, Full Stack](/coding-for-class-8)
- [Coding for Class 4: Scratch, Block Coding & First Python for 9 Year Olds](/coding-for-class-4)
- [Coding for Class 7: Python, JavaScript](/coding-for-class-7)

### Learn more

- [CS Summer Programs for High School Students: 2027 Guide](/computer-science-summer-programs-for-high-school-students)
- [AI or Computer Applications in Class 10? 417, 402 or 165](/ai-vs-computer-applications-class-10)
- [The Course Atlas: Every Coding, AI & Mathematics Course (Kids, Teens](/course-atlas)
- [Cambridge IGCSE Computer Science Tuition](/cambridge-igcse-computer-science-tuition)

### Free resources

- [Python Tutorial for Beginners: Complete Guide](/resources/python)
- [Project: Build an Interactive Portfolio Website](/resources/javascript/project-interactive-portfolio)
- [Your First Python Program](/resources/python/your-first-python-program)
- [Exception Handling in Python](/resources/python/exception-handling)

### From the blog

- [Python Programs for Class 11 CBSE (CS and IP) With Output](/blog/python-programs-for-class-11)
- [The IB Computer Science IA No Longer Needs a Client](/blog/ib-computer-science-ia-client-rule-2027)
- [IGCSE 0478 Pseudocode: The Rules Examiners Mark](/blog/igcse-computer-science-0478-pseudocode-guide)

### Start here

- [About Modern Age Coders, teaching since 2020](/about)
- [Modern Age Coders pricing, one honest price per plan](/pricing)

---

*Canonical: https://learn.modernagecoders.com/cbse-class-12-computer-science-csv-and-binary-files*
