Skip to content

Instantly share code, notes, and snippets.

@maxf
Last active October 28, 2025 17:57
Show Gist options
  • Select an option

  • Save maxf/debb8cbdaa84db685a15f98068f143fb to your computer and use it in GitHub Desktop.

Select an option

Save maxf/debb8cbdaa84db685a15f98068f143fb to your computer and use it in GitHub Desktop.
Code example
# This code has been written by a junior developer. It works but as a senior developer
# do you have some suggestions on how to improve it?
# Think about edge cases, file sizes growing, efficiency, resilience to change,
# how it can better use Python's built-in features and be made more Pythonic and why this would be more helpful
import csv
import json
from datetime import datetime
# Load data from CSV
file_path = 'data.csv'
data = []
headers = []
try:
f = open(file_path, 'r')
reader = csv.DictReader(f)
headers = reader.fieldnames
for row in reader:
data.append(row)
f.close()
except:
print("Error loading file")
# Clean and process data
cleaned_data = []
for row in data:
if all(row.values()):
cleaned_data.append(row)
data = cleaned_data
# Convert data types
for row in data:
for key in row.keys():
value = row[key]
if value.isdigit():
row[key] = int(value)
elif value.replace('.', '', 1).isdigit():
row[key] = float(value)
# Calculate metrics
totals = {}
counts = {}
for row in data:
for key, value in row.items():
if type(value) == int or type(value) == float:
if key not in totals:
totals[key] = 0
counts[key] = 0
totals[key] = totals[key] + value
counts[key] = counts[key] + 1
metrics = {}
for key in totals.keys():
metrics[key + '_average'] = totals[key] / counts[key]
# Export to CSV
output_path = 'output'
f = open(output_path + '.csv', 'w', newline='')
writer = csv.DictWriter(f, fieldnames=headers)
writer.writeheader()
for row in data:
writer.writerow(row)
f.close()
# Export to JSON
f = open(output_path + '.json', 'w')
json.dump(data, f, indent=2)
f.close()
print("Processing complete")
print("Metrics:", metrics)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment