Q1. You have a CSV file ''data.csv'' with columns: age, income. Write code to read the file line by line, skip header, and store ages in a list.
with open('data.csv') as f:
lines = f.readlines()[1:] # skip header
ages = [int(line.split(',')[0]) for line in lines]
# Using csv module
import csv
with open('data.csv') as f:
reader = csv.reader(f)
next(reader)
ages = [int(row[0]) for row in reader]Q2. Write a Python script to write a list of predictions [0.5, 0.7, 0.9] to a text file ''predictions.txt'', one per line.
predictions = [0.5, 0.7, 0.9]
with open('predictions.txt', 'w') as f:
for pred in predictions:
f.write(str(pred) + 'n')
# or use writelines:
# f.writelines(f'{pred}n' for pred in predictions)This is essential for saving model outputs.Q3. You have a large JSON file ''model_weights.json'' containing a dictionary. Load it, modify a key ''layer1'' to new values, and save it back.
import json
with open('model_weights.json') as f:
data = json.load(f)
data['layer1'] = [0.1, 0.2, 0.3]
with open('model_weights.json', 'w') as f:
json.dump(data, f, indent=2)JSON is common for model serialization.Q4. You have a binary file ''data.bin'' containing 1000 floats. Read them into a list using the struct module or numpy. Which is easier?
import numpy as np
data = np.fromfile('data.bin', dtype=np.float32)Using numpy is easier and efficient for numerical arrays. Use open(file, ''rb'') for binary reading.Q5. Write a function that appends a new prediction to a CSV log file with timestamp. The file has headers ''timestamp'',''prediction''. Create file if not exists.
import csv, datetime, os
def log_prediction(pred):
file_exists = os.path.isfile('log.csv')
with open('log.csv', 'a', newline='') as f:
writer = csv.writer(f)
if not file_exists:
writer.writerow(['timestamp', 'prediction'])
writer.writerow([datetime.datetime.now(), pred])This logs model predictions over time.