Skip to content

Instantly share code, notes, and snippets.

@MrZombie69232
Created September 1, 2020 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrZombie69232/fa404773b3b14e30762e87614ebd7c27 to your computer and use it in GitHub Desktop.
Save MrZombie69232/fa404773b3b14e30762e87614ebd7c27 to your computer and use it in GitHub Desktop.
reads csv files
# creating function to split header
def parse_headers(header_line):
return header_line.strip().split(',')
# function to replace missing values
def parse_values(data_line):
values = []
for items in data_line.strip().split(','):
if items == '': # check if there is an empty string
values.append(0.0)
else:
values.append(float(items))
return values
# function to create dictionary of items
def create_item_dict (values , headers):
results = {}
for value , header in zip(values , headers):
results[header] = value
return results
# creating a read_csv function
def read_csv (path):
result = []
# open the file in read mode
with open (path , 'r') as f:
# get a list of lines
lines = f.readlines()
# parse the header
headers = parse_headers(lines[0])
# loop over the remaining lines
for data_line in lines[1:]:
# parse the values
values = parse_values(data_line)
# create a dictionary using values and headers
item_dict = create_item_dict(values , headers)
# add the dictionary to the result
result.append(item_dict)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment