Last active
November 16, 2020 20:09
-
-
Save jwhett/9a1a0a83300ed30fb035140dff263c90 to your computer and use it in GitHub Desktop.
Python CSV demonstration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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