Q1. Scenario: 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:]; ages = [int(line.split('','')[0]) for line in lines]. Alternatively, use 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. Scenario: 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.
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. Scenario: 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. Scenario: You have a binary file 'data.bin' containing 1000 floats. Read them into a list using the struct module or numpy. Which is easier?
Using numpy: import numpy as np; data = np.fromfile(''data.bin'', dtype=np.float32). For struct, more manual. Numpy efficient for numerical arrays. Use with open file in ''rb'' mode for binary reading.
Q5. Scenario: 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; 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.
