Exit Chapter 05B ยท ๐Ÿ” File Handling in Python (Binary & CSV file) โ€” Quiz

Playing as a guest? to earn XP and track your progress.

Question 1 of 56 0 correct so far

๐Ÿ” File Handling in Python (Binary & CSV file) Quiz

Q1.

Which Python module is used to handle binary files through serialization?

Explanation

The built-in pickle module is used for binary file handling in Python. It serializes (pickles) Python objects to bytes and deserializes (unpickles) them back.

Q2.

What is the process of converting a Python object into a byte stream called?

Explanation

Pickling (also called Serialization) is the process of converting a Python object into a byte stream so it can be stored in a binary file.

Q3.

What is the process of reconstructing a Python object from bytes stored in a binary file called?

Explanation

Unpickling (also called Deserialization) is the reverse process โ€” reading bytes from a binary file and reconstructing the original Python object.

Q4.

Which function is used to write a Python object to a binary file?

Explanation

pickle.dump(object, file_object) serializes the Python object and writes it to the binary file opened in 'wb' or 'ab' mode.

Q5.

Which function is used to read a Python object from a binary file?

Explanation

pickle.load(file_object) reads and reconstructs the next Python object from the binary file opened in 'rb' mode.

Q6.

What is the correct syntax for pickle.dump()?

Explanation

The correct syntax is pickle.dump(object, file_object) โ€” the object to write comes first, then the file handle opened in binary write mode.

Q7.

Which file mode is used to write a binary file from scratch (creating new or overwriting existing)?

Explanation

'wb' (write binary) opens a file for writing in binary mode. It creates the file if it doesn't exist, or overwrites all existing content if it does.

Q8.

Which file mode is used to read records from an existing binary file?

Explanation

'rb' (read binary) opens an existing binary file for reading. It raises FileNotFoundError if the file does not exist.

Q9.

Which mode is used to add new records to a binary file WITHOUT deleting existing records?

Explanation

'ab' (append binary) opens the file for writing at the end, preserving all existing records. It is the safe way to add new data to a binary file.

Q10.

What exception is raised by pickle.load() when there are no more objects to read in a binary file?

Explanation

EOFError (End of File Error) is raised by pickle.load() when it tries to read past the last object in the file. This is how Python signals 'no more records'.

Q11.

What is the standard pattern to read ALL records from a binary file?

Explanation

The standard CBSE pattern: while True: โ†’ try: record = pickle.load(f) โ†’ process โ†’ except EOFError: break. This reads records one by one until EOF.

Q12.

What is the common file extension used for binary (pickle) files in CBSE programs?

Explanation

In CBSE exam programs, binary pickle files conventionally use the .dat extension (e.g., students.dat). Python doesn't enforce this โ€” it's a convention.

Q13.

Which of the following is TRUE about binary files?

Explanation

Binary files store data as raw bytes โ€” not human-readable. Opening them in Notepad shows garbage characters. Python's pickle is needed to decode them.

Q14.

Which of the following Python objects CAN be stored in a binary file using pickle?

Explanation

The pickle module can serialize any Python object โ€” integers, strings, lists, dictionaries, tuples, custom class instances โ€” and perfectly restore them on loading.

Q15.

What is the advantage of binary files over text files for storing student records?

Explanation

Binary files preserve Python data types. A dict stored with pickle is loaded back as a dict with correct types. Text files convert everything to strings requiring manual conversion.

Q16.

What is the output?

import pickle
f = open("test.dat", "wb")
student = {"name": "Aman", "marks": 95}
pickle.dump(student, f)
f.close()

f = open("test.dat", "rb")
data = pickle.load(f)
print(type(data))
f.close()
Explanation

pickle.dump() stores the dict as bytes. pickle.load() perfectly reconstructs the original Python object โ€” a dict. So type(data) is <class 'dict'>.

Q17.

To update a record in a binary pickle file, the correct approach is:

Explanation

The CBSE-standard update pattern: (1) Read ALL records into a list using 'rb', (2) Modify target record in the list, (3) Rewrite ALL records using 'wb'. Direct in-place editing corrupts pickle files.

Q18.

Why can't you update a single record in-place in a binary pickle file?

Explanation

Each pickled object can have a different byte size. Overwriting one record may shift all byte positions after it, corrupting every subsequent record. Always use read-all โ†’ modify โ†’ write-all.

Q19.

Which step comes FIRST when deleting a record from a binary file?

Explanation

The first step is always to open the file in 'rb' mode and read ALL records into a Python list. Then filter out the target record from the list, and finally rewrite all remaining records using 'wb'.

Q20.

What is the correct way to write multiple student dictionaries one by one to a binary file?

Explanation

Each pickle.dump() call writes one object. To write multiple records, loop through the list and dump each dictionary individually. This allows reading them back one at a time.

Q21.

What does pickle.load() return when called on a binary file?

Explanation

pickle.load() deserializes the bytes and returns the original Python object โ€” with its exact type (dict, list, int, etc.) perfectly preserved.

Q22.

CSV stands for:

Explanation

CSV stands for Comma-Separated Values โ€” a plain text format where each row is a line and each column is separated by a comma.

Q23.

Which Python module is used to read and write CSV files?

Explanation

Python's built-in csv module handles CSV files. It requires import csv โ€” no installation needed.

Q24.

Which special parameter MUST be included when opening a CSV file for writing to avoid blank rows on Windows?

Explanation

newline='' prevents Python from adding extra blank lines between data rows on Windows. It is essential when opening CSV files for writing: open('data.csv', 'w', newline='').

Q25.

Which object is used to write rows as lists to a CSV file?

Explanation

csv.writer(file_object) creates a writer that accepts lists or tuples and writes each one as a row in the CSV file.

Q26.

Which object is used to write rows as dictionaries to a CSV file?

Explanation

csv.DictWriter(file_object, fieldnames=fields) creates a writer that accepts dictionaries. Keys automatically map to the correct column.

Q27.

Which method writes a single row (as a list) to a CSV file?

Explanation

writer.writerow(list) writes a single list as one row in the CSV file. Each element in the list becomes one column value.

Q28.

Which method writes ALL rows (as a list of lists) to a CSV file in one call?

Explanation

writer.writerows(list_of_lists) writes multiple rows in one efficient call. Each inner list becomes one row in the CSV file.

Q29.

Which method is used ONLY with csv.DictWriter to write column headers?

Explanation

writer.writeheader() is exclusive to csv.DictWriter. It writes the fieldnames list as the first (header) row of the CSV file.

Q30.

Which object reads each row of a CSV file as a list?

Explanation

csv.reader(file_object) reads each row as a list of strings. Access columns by position: row[0], row[1], etc.

Q31.

Which object reads each row of a CSV file as a dictionary with column headers as keys?

Explanation

csv.DictReader(file_object) reads each row as a dictionary. The first row of the CSV is automatically used as keys. Access columns by name: row['Name'].

Q32.

What data type does csv.reader return for ALL values (including numbers)?

Explanation

csv.reader returns all values as strings โ€” even if the original was a number. You must manually convert: int(row[2]) or float(row[3]).

Q33.

What is the output?

import csv
with open("data.csv", "w", newline='') as f:
    writer = csv.writer(f)
    writer.writerow(["Name", "Marks"])
    writer.writerow(["Aman", 95])

with open("data.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
Explanation

csv.reader returns all values as strings. So 95 (integer written) comes back as '95' (string). Output: ['Name', 'Marks'] then ['Aman', '95'].

Q34.

Which of the following correctly opens a CSV file for writing in Python?

Explanation

The correct way is open('data.csv', 'w', newline=''). The newline='' parameter is required to prevent extra blank lines from being inserted between rows on Windows.

Q35.

After reading a CSV file with csv.reader, how do you skip the header row?

Explanation

next(reader) reads and discards the first row (the header). Subsequent iterations in for row in reader: then start from the first data row.

Q36.

What is the advantage of csv.DictReader over csv.reader?

Explanation

csv.DictReader lets you access column values by their name (row['Marks']), making code cleaner and less error-prone than using index positions (row[2]).

Q37.

To append new rows to an existing CSV file without overwriting existing data, which mode should you use?

Explanation

Mode 'a' (append) with newline='': open('data.csv', 'a', newline=''). This places the write pointer at the end, preserving all existing rows.

Q38.

Which statement correctly imports both pickle and csv modules?

Explanation

import pickle, csv is the correct way to import both modules in one statement. Both are built-in โ€” no installation required.

Q39.

What is the main difference between binary files (pickle) and CSV files?

Explanation

Binary/pickle files preserve Python data types (int stays int, dict stays dict). CSV files store everything as plain text strings โ€” types must be converted manually when reading.

Q40.

Which file type can be directly opened in Microsoft Excel?

Explanation

CSV files can be directly opened in Excel, Google Sheets, and any spreadsheet software. Binary/pickle files are not human-readable and cannot be opened in Excel.

Q41.

How is End-of-File (EOF) detected differently in binary files vs CSV files?

Explanation

In binary files, pickle.load() raises EOFError at EOF โ€” you must catch it. In CSV files, for row in reader: ends naturally when all rows are read โ€” no exception needed.

Q42.

What is the output?

import pickle
f = open("test.dat", "wb")
pickle.dump({"roll": 1, "marks": 90}, f)
pickle.dump({"roll": 2, "marks": 85}, f)
f.close()

f = open("test.dat", "rb")
count = 0
while True:
    try:
        pickle.load(f)
        count += 1
    except EOFError:
        break
f.close()
print(count)
Explanation

Two objects were dumped. Each pickle.load() reads one object. After two successful loads, the third raises EOFError โ†’ break. count = 2.

Q43.

Which of these is the correct way to create a csv.DictWriter?

Explanation

csv.DictWriter(file_object, fieldnames=['Name','Marks']) is correct. The fieldnames parameter specifies the column order and is required.

Q44.

What does writeheader() write to the CSV file?

Explanation

writeheader() writes the fieldnames list as the first row of the CSV โ€” the column header row (e.g., Name,Roll,Marks,Grade).

Q45.

What is the correct order of steps to write data using csv.DictWriter?

Explanation

Correct order: (1) Create DictWriter(f, fieldnames=...), (2) Call writeheader() to write the header row, (3) Call writerow(dict) for each data record.

Q46.

In the binary file update pattern, why is the file opened in 'wb' mode (not 'ab') when writing back?

Explanation

Opening in 'wb' completely erases the existing content and writes the entire modified list fresh. Using 'ab' would add the modified records at the end while keeping the old (unmodified) ones, creating duplicates.

Q47.

What is the output?

import csv
with open('marks.csv', 'w', newline='') as f:
    w = csv.writer(f)
    w.writerows([[1,'Aman',95],[2,'Priya',88]])

with open('marks.csv', 'r') as f:
    r = csv.reader(f)
    for row in r:
        print(row[2])
Explanation

csv.reader returns all values as strings. So row[2] gives '95' (not 95). Output: '95' then '88' printed as strings without quotes (but they ARE strings internally).

Q48.

Which of the following is a key advantage of CSV files over binary files?

Explanation

CSV files are human-readable plain text and can be opened directly in Excel, Google Sheets, and imported into databases โ€” making them ideal for data exchange.

Q49.

Which module's DictReader automatically uses the first row of the CSV as dictionary keys?

Explanation

csv.DictReader automatically reads the first row as column headers and uses them as dictionary keys for all subsequent data rows.

Q50.

What happens if you forget newline='' when writing a CSV file on Windows?

Explanation

Without newline='', Python adds its own newline translation on Windows, causing an extra blank line between every data row in the CSV file, corrupting its structure.

Q51.

To search for a student with a specific roll number in a binary file, which pattern is used?

Explanation

The correct search pattern: open 'rb' โ†’ while True: โ†’ try: record = pickle.load(f) โ†’ check condition โ†’ except EOFError: break. There is no built-in search in pickle.

Q52.

What does csv.writer(f).writerows([[1,'A'],[2,'B']]) write to the file?

Explanation

writerows() writes each inner list as a separate row: 1,A on line 1 and 2,B on line 2. It is equivalent to calling writerow([1,'A']) followed by writerow([2,'B']).

Q53.

Which file type requires import pickle to work with?

Explanation

Binary files handled via Python's serialization mechanism require import pickle. The pickle module provides dump() and load() functions for reading and writing.

Q54.

When reading a CSV file with csv.DictReader, how do you access the value of column 'Marks' for a row?

Explanation

csv.DictReader returns each row as a dictionary. Column values are accessed by their header name as a key: row['Marks'].

Q55.

What is the output?

import pickle
f = open("demo.dat", "wb")
pickle.dump([1, 2, 3], f)
f.close()

f = open("demo.dat", "rb")
data = pickle.load(f)
print(data[1])
f.close()
Explanation

pickle.dump([1,2,3], f) stores the list. pickle.load(f) retrieves it as a Python list. data[1] accesses index 1 โ†’ value is 2.

Q56.

Which of the following correctly reads a CSV file and converts the 'Marks' column to integer?

Explanation

CSV values are always strings. To get an integer, you must explicitly convert: int(row['Marks']). Without this, arithmetic operations on CSV numbers will fail with TypeError.