Playing as a guest? to earn XP and track your progress.
๐ File Handling in Python (Binary & CSV file) Quiz
๐ File Handling in Python (Binary & CSV file)
Which Python module is used to handle binary files through serialization?
binary
struct
pickle
shelve
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.
What is the process of converting a Python object into a byte stream called?
Deserialization
Compilation
Pickling (Serialization)
Encoding
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.
What is the process of reconstructing a Python object from bytes stored in a binary file called?
Pickling
Unpickling (Deserialization)
Decoding
Parsing
Unpickling (also called Deserialization) is the reverse process โ reading bytes from a binary file and reconstructing the original Python object.
Which function is used to write a Python object to a binary file?
pickle.write()
pickle.store()
pickle.dump()
pickle.save()
pickle.dump(object, file_object) serializes the Python object and writes it to the binary file opened in 'wb' or 'ab' mode.
Which function is used to read a Python object from a binary file?
pickle.read()
pickle.get()
pickle.fetch()
pickle.load()
pickle.load(file_object) reads and reconstructs the next Python object from the binary file opened in 'rb' mode.
What is the correct syntax for pickle.dump()?
pickle.dump(file, object)
pickle.dump(object, file_object)
pickle.dump(filename, object)
dump.pickle(object, file)
The correct syntax is pickle.dump(object, file_object) โ the object to write comes first, then the file handle opened in binary write mode.
Which file mode is used to write a binary file from scratch (creating new or overwriting existing)?
'rb'
'ab'
'wb'
'rb+'
'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.
Which file mode is used to read records from an existing binary file?
'wb'
'ab'
'rb'
'r'
'rb' (read binary) opens an existing binary file for reading. It raises FileNotFoundError if the file does not exist.
Which mode is used to add new records to a binary file WITHOUT deleting existing records?
'wb'
'rb'
'ab'
'rb+'
'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.
What exception is raised by pickle.load() when there are no more objects to read in a binary file?
FileNotFoundError
StopIteration
EOFError
IndexError
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'.
What is the standard pattern to read ALL records from a binary file?
for record in file:
while file.read(): ...
while True: try: pickle.load() except EOFError: break
pickle.loadall(file)
The standard CBSE pattern: while True: โ try: record = pickle.load(f) โ process โ except EOFError: break. This reads records one by one until EOF.
What is the common file extension used for binary (pickle) files in CBSE programs?
.bin
.dat
.pkl
.obj
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.
Which of the following is TRUE about binary files?
They can be opened in any text editor
They store data as human-readable characters
They are not human-readable and store raw bytes
They only store integers and floats
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.
Which of the following Python objects CAN be stored in a binary file using pickle?
Only integers
Only strings and lists
Only dictionaries
Any Python object โ list, dict, tuple, class instance
The pickle module can serialize any Python object โ integers, strings, lists, dictionaries, tuples, custom class instances โ and perfectly restore them on loading.
What is the advantage of binary files over text files for storing student records?
Binary files are human-readable
No data type conversion needed โ int stays int, list stays list
Binary files are smaller
Binary files can be opened in Excel
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.
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()<class 'str'>
<class 'bytes'>
<class 'dict'>
<class 'list'>
pickle.dump() stores the dict as bytes. pickle.load() perfectly reconstructs the original Python object โ a dict. So type(data) is <class 'dict'>.
To update a record in a binary pickle file, the correct approach is:
Open in 'rb+' and overwrite the specific record directly
Open in 'wb', seek to the record, and rewrite it
Read ALL records โ modify target in memory โ write ALL back using 'wb'
Delete the file and recreate from scratch
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.
Why can't you update a single record in-place in a binary pickle file?
Python does not support binary mode
pickle.dump() does not support updating
Pickle records vary in size โ overwriting one shifts byte positions and corrupts the rest
Binary files are read-only
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.
Which step comes FIRST when deleting a record from a binary file?
Open the file in 'wb' mode
Open the file in 'rb' mode and read all records into a list
Call pickle.dump() to remove the record
Use del() on the file object
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'.
What is the correct way to write multiple student dictionaries one by one to a binary file?
pickle.dump(all_students, f)
for student in students: pickle.dump(student, f)
pickle.dumpall(students, f)
f.write(students)
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.
What does pickle.load() return when called on a binary file?
A string of bytes
The raw bytes
The reconstructed Python object (in its original type)
A file object
pickle.load() deserializes the bytes and returns the original Python object โ with its exact type (dict, list, int, etc.) perfectly preserved.
CSV stands for:
Comma Stored Values
Comma Separated Values
Character String Values
Compiled Structured Values
CSV stands for Comma-Separated Values โ a plain text format where each row is a line and each column is separated by a comma.
Which Python module is used to read and write CSV files?
pandas
csv
xlrd
file
Python's built-in csv module handles CSV files. It requires import csv โ no installation needed.
Which special parameter MUST be included when opening a CSV file for writing to avoid blank rows on Windows?
encoding='utf-8'
newline=''
mode='csv'
lineterminator=''
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='').
Which object is used to write rows as lists to a CSV file?
csv.DictWriter
csv.writer
csv.FileWriter
csv.rowwriter
csv.writer(file_object) creates a writer that accepts lists or tuples and writes each one as a row in the CSV file.
Which object is used to write rows as dictionaries to a CSV file?
csv.writer
csv.DictWriter
csv.DictSaver
csv.MapWriter
csv.DictWriter(file_object, fieldnames=fields) creates a writer that accepts dictionaries. Keys automatically map to the correct column.
Which method writes a single row (as a list) to a CSV file?
writerows()
writeline()
writerow()
writedata()
writer.writerow(list) writes a single list as one row in the CSV file. Each element in the list becomes one column value.
Which method writes ALL rows (as a list of lists) to a CSV file in one call?
writerow()
writeheader()
writerows()
writelines()
writer.writerows(list_of_lists) writes multiple rows in one efficient call. Each inner list becomes one row in the CSV file.
Which method is used ONLY with csv.DictWriter to write column headers?
writerow(['headers'])
writecols()
writeheader()
writekeys()
writer.writeheader() is exclusive to csv.DictWriter. It writes the fieldnames list as the first (header) row of the CSV file.
Which object reads each row of a CSV file as a list?
csv.DictReader
csv.reader
csv.listReader
csv.rowReader
csv.reader(file_object) reads each row as a list of strings. Access columns by position: row[0], row[1], etc.
Which object reads each row of a CSV file as a dictionary with column headers as keys?
csv.reader
csv.DictReader
csv.MapReader
csv.headerReader
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'].
What data type does csv.reader return for ALL values (including numbers)?
int
float
str (string)
depends on value
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]).
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)['Name', 'Marks']\n['Aman', 95]
['Name', 'Marks']\n['Aman', '95']
Name,Marks\nAman,95
Error
csv.reader returns all values as strings. So 95 (integer written) comes back as '95' (string). Output: ['Name', 'Marks'] then ['Aman', '95'].
Which of the following correctly opens a CSV file for writing in Python?
open('data.csv', 'w')
open('data.csv', 'wb')
open('data.csv', 'w', newline='')
open('data.csv', 'wcsv')
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.
After reading a CSV file with csv.reader, how do you skip the header row?
reader.skip(1)
next(reader)
reader.skipheader()
del reader[0]
next(reader) reads and discards the first row (the header). Subsequent iterations in for row in reader: then start from the first data row.
What is the advantage of csv.DictReader over csv.reader?
DictReader is faster
DictReader reads binary files too
Access columns by name (row['Name']) instead of by position (row[0])
DictReader auto-converts strings to integers
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]).
To append new rows to an existing CSV file without overwriting existing data, which mode should you use?
'w'
'r'
'a'
'a+'
Mode 'a' (append) with newline='': open('data.csv', 'a', newline=''). This places the write pointer at the end, preserving all existing rows.
Which statement correctly imports both pickle and csv modules?
import pickle, csv
from file import pickle, csv
include pickle; include csv
import binary.pickle and csv
import pickle, csv is the correct way to import both modules in one statement. Both are built-in โ no installation required.
What is the main difference between binary files (pickle) and CSV files?
Binary files are text; CSV files are binary
Binary files preserve Python types; CSV files store everything as strings
CSV files use pickle module; binary files use csv module
Both are identical
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.
Which file type can be directly opened in Microsoft Excel?
Binary .dat file
Pickle .pkl file
CSV .csv file
All of the above
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.
How is End-of-File (EOF) detected differently in binary files vs CSV files?
Both use EOFError
Binary uses EOFError exception; CSV loop ends naturally
Both end the loop naturally
CSV uses EOFError; Binary loop ends naturally
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.
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)1
2
0
Error
Two objects were dumped. Each pickle.load() reads one object. After two successful loads, the third raises EOFError โ break. count = 2.
Which of these is the correct way to create a csv.DictWriter?
csv.DictWriter(f)
csv.DictWriter(f, fieldnames=['Name','Marks'])
csv.DictWriter('Name','Marks')
csv.DictWriter(fields=['Name','Marks'])
csv.DictWriter(file_object, fieldnames=['Name','Marks']) is correct. The fieldnames parameter specifies the column order and is required.
What does writeheader() write to the CSV file?
The first data row
The column names (field names) as the first row
A blank line as header separator
The file metadata
writeheader() writes the fieldnames list as the first row of the CSV โ the column header row (e.g., Name,Roll,Marks,Grade).
What is the correct order of steps to write data using csv.DictWriter?
writerow() โ DictWriter() โ writeheader()
DictWriter() โ writeheader() โ writerow()
writeheader() โ DictWriter() โ writerow()
open() โ writerow() โ DictWriter()
Correct order: (1) Create DictWriter(f, fieldnames=...), (2) Call writeheader() to write the header row, (3) Call writerow(dict) for each data record.
In the binary file update pattern, why is the file opened in 'wb' mode (not 'ab') when writing back?
'ab' is not valid for pickle
'wb' is faster than 'ab'
'wb' overwrites all content, replacing with the complete modified list
'ab' adds to the end which would create duplicates
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.
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])95\n88
'95'\n'88'
95.0\n88.0
Error
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).
Which of the following is a key advantage of CSV files over binary files?
CSV preserves Python data types
CSV files can store class instances
CSV is human-readable and compatible with spreadsheet tools
CSV is faster to read
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.
Which module's DictReader automatically uses the first row of the CSV as dictionary keys?
pickle
json
csv
os
csv.DictReader automatically reads the first row as column headers and uses them as dictionary keys for all subsequent data rows.
What happens if you forget newline='' when writing a CSV file on Windows?
The file is not created
A SyntaxError is raised
Blank lines are inserted between each data row
The CSV becomes a binary file
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.
To search for a student with a specific roll number in a binary file, which pattern is used?
Open 'r' โ read line by line โ compare
Open 'rb' โ while True โ try pickle.load() โ compare โ except EOFError: break
Open 'rb' โ pickle.search(roll)
Open 'rb' โ for record in file: compare
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.
What does csv.writer(f).writerows([[1,'A'],[2,'B']]) write to the file?
1,A,2,B on one line
1,A on line 1 and 2,B on line 2
[[1,'A'],[2,'B']]
Error
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']).
Which file type requires import pickle to work with?
Text files (.txt)
CSV files (.csv)
Binary files (.dat)
HTML files (.html)
Binary files handled via Python's serialization mechanism require import pickle. The pickle module provides dump() and load() functions for reading and writing.
When reading a CSV file with csv.DictReader, how do you access the value of column 'Marks' for a row?
row[2]
row.Marks
row['Marks']
row.get(2)
csv.DictReader returns each row as a dictionary. Column values are accessed by their header name as a key: row['Marks'].
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()1
2
[1,2,3]
Error
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.
Which of the following correctly reads a CSV file and converts the 'Marks' column to integer?
row['Marks']
pickle.load(row['Marks'])
int(row['Marks'])
float(row[1])
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.