Skip to content

Instantly share code, notes, and snippets.

@jwhett
Last active November 16, 2020 20:09
Show Gist options
  • Save jwhett/9a1a0a83300ed30fb035140dff263c90 to your computer and use it in GitHub Desktop.
Save jwhett/9a1a0a83300ed30fb035140dff263c90 to your computer and use it in GitHub Desktop.
Python CSV demonstration
import csv
import math
def diameter(rad):
return rad*2
def surface(rad):
return 4*math.pi*pow(rad,2)
def volume(rad):
return (4/3)*(math.pi*pow(rad,3))
with open('spheres.csv', 'r+') as input_csv:
# Read the CSV.
csv_reader = csv.reader(input_csv, delimiter=',')
# Set a tracker for if we're reading
# the header row.
header = True
# Empty list of rows that we'll store
# use to store our calculations.
output_csv = []
for row in csv_reader:
# Are we at the header row?
if header:
# Add new headers.
header = False
output_csv.append(row + ["diameter","surface","volume"])
# Go to the next line of the file.
continue
# Find and assign the radius.
radius = float(row[2])
# Append our calculations to the end of each row.
output_csv.append(row + [diameter(radius),surface(radius),volume(radius)])
# Set position to the beginning of the file.
input_csv.seek(0)
# Write our new, calculated data to the original CSV.
csv.writer(input_csv, delimiter=',').writerows(output_csv)
first second radius diameter surface volume
this is 1 2.0 12.566370614359172 4.1887902047863905
this is 2 4.0 50.26548245743669 33.510321638291124
this is 3 6.0 113.09733552923255 113.09733552923254
first second radius
this is 1
this is 2
this is 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment