Last active
April 4, 2022 23:27
-
-
Save amywieliczka/88632fc444dad150244459bb24c472dd to your computer and use it in GitHub Desktop.
Reading a csv file
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 | |
def read_csv_file_into_array(filename): | |
csv_file = open(filename) | |
lines = csv.reader(csv_file, delimiter=',') | |
data = [] | |
for row_num, row in enumerate(lines): | |
if row_num == 0: | |
continue | |
if row_num == 1: | |
header = row | |
else: | |
row_dict = {} | |
for cell_num, cell in enumerate(row): | |
try: | |
row_dict[header[cell_num]] = float(cell) | |
except ValueError: | |
row_dict[header[cell_num]] = cell | |
data.append(row_dict) | |
return data | |
data1 = read_csv_file_into_array(<filename1>) | |
data2 = read_csv_file_into_array(<filename2>) | |
# [ | |
# {'Wavelength (nm)': 850.0, 'Abs': 0.06241456047, '': ''}, | |
# {'Wavelength (nm)': 849.0, 'Abs': 0.05203075707, '': ''}, | |
# {'Wavelength (nm)': 848.0, 'Abs': 0.06630643457, '': ''}, | |
# ... | |
# ] | |
# So now you can access the wavelength of | |
# the first row by data[0]['Wavelength (nm)'] | |
# rather than data[0][0] | |
# it just makes your code a bit easier to read |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment