Answer the questions based on the code below with proper justifications.…
2026
Answer the questions based on the code below with proper justifications.
import pickle
import csv
records = [
{'id': 1, 'name': 'Alice', 'score': 95.5},
{'id': 2, 'name': 'Bob', 'score': 87.0},
{'id': 3, 'name': 'Charlie', 'score': 91.3}
]
with open('data.pkl', 'wb') as f:
pickle.dump(records, f)
with open('data.csv', 'w', newline='') as f:
writer = csv.DictWriter(
f,
fieldnames=['id', 'name', 'score']
)
writer.writeheader()
writer.writerows(records)
(i) What is the difference between a text file and a binary file at the byte level? Why can't you read data.pkl in a text editor meaningfully?
(ii) What is pickling? Explain the security risk of unpickling data from an unknown source. Under what conditions could a malicious pickle file execute arbitrary code?
(iii) What is the purpose of newline='' when opening a CSV on Windows? What specific problem does omitting it cause?
(iv) Write a program that reads data.pkl and data.csv, merges by id, adds a grade field — A if score >= 90 else B — and writes to results.csv. Include proper exception handling.
Show answer & explanation
(i) Difference Between Text File and Binary File
Byte-Level Difference
Text files store data as readable characters.
Each byte (or group of bytes) represents a character using encoding schemes such as ASCII or UTF-8.Binary files store data as raw bytes exactly as they are stored in computer memory, without any character encoding.
Why data.pkl Cannot Be Read Properly in a Text Editor
data.pkl is a binary file created using the pickle module.
It contains serialized Python objects in binary form.
When a text editor opens this file, it tries to interpret raw binary bytes as text characters, which results in unreadable or garbled symbols.
(ii) Pickling and Security Risks
Pickling
Pickling is the process of converting Python objects into a byte stream (serialization) so they can be stored in files or transmitted over a network.
Example:
pickle.dump(records, f)The reverse process is called unpickling.
pickle.load(f)Security Risk of Unpickling
The pickle module is not secure for untrusted data.
A malicious pickle file may contain harmful instructions that can execute arbitrary code during unpickling.
Condition for Arbitrary Code Execution
During unpickling, Python may automatically execute functions returned by the __reduce__() method of an object.
An attacker can craft a malicious pickle file that calls dangerous functions such as:
os.system()Thus, if pickle.load() is used on data from an unknown or untrusted source, arbitrary system commands may execute.
(iii) Purpose of newline='' in CSV on Windows
newline='' prevents extra blank lines while writing CSV files on Windows.
The CSV module already handles newline characters internally.
If newline='' is omitted:
Windows automatically converts
\ninto\r\nThe CSV module also writes
\r\nThis causes double newline translation
As a result, extra empty rows appear between records in the CSV file.
Therefore, using:
open('data.csv', 'w', newline='')ensures correct CSV formatting.
(iv) Program to Read, Merge, Add Grade, and Write results.csv
import pickle
import csv
try:
# Read data from pickle file
with open('data.pkl', 'rb') as pf:
pkl_data = pickle.load(pf)
# Read data from CSV file
with open('data.csv', 'r', newline='') as cf:
reader = csv.DictReader(cf)
csv_data = list(reader)
merged_records = []
# Merge records and assign grades
for rec in pkl_data:
score = float(rec['score'])
grade = 'A' if score >= 90 else 'B'
merged_records.append({
'id': int(rec['id']),
'name': rec['name'],
'score': score,
'grade': grade
})
# Write output to results.csv
with open('results.csv', 'w', newline='') as rf:
fields = ['id', 'name', 'score', 'grade']
writer = csv.DictWriter(rf, fieldnames=fields)
writer.writeheader()
writer.writerows(merged_records)
print("results.csv created successfully")
except FileNotFoundError:
print("Error: File not found")
except pickle.UnpicklingError:
print("Error: Invalid pickle file")
except ValueError as e:
print("Value Error:", e)
except Exception as e:
print("Unexpected Error:", e)Output of results.csv
id,name,score,grade
1,Alice,95.5,A
2,Bob,87.0,B
3,Charlie,91.3,AA video solution is available for this question — log in and enroll to watch it.