I'm trying to write a function in python, which reads csv files and returns them nicely formatted. The input files are just standard csv files. Where each line represents a person. The output format should look like:
[
("Age", "Gender", "Weight (kg)", "Height (cm)"),
("28", "Female", "58", "168"),
("33", "Male", "", "188")
]
The thing is just don't know how I can do this. I know that I can loop through every element in my list of lists and print it, but I would like to return them as above. The only format I manage to end up with looks like:
[('Age', 'Gender', 'Weight (kg)', 'Height (cm)'), ('28', 'Female', '58', '168'), ('33', 'Male', '', '188')]
In case anyone need to see my code(I guess it's not nicely coded at all but I'm learning):
def read_csv(path):
newlist = []
with open("example.csv", "r") as f:
nr_of_lines = 0
for line in f.readlines():
counter = 0
nr_of_lines += 1
while "," in line:
idx = line.find(",")
entry = line[0:idx]
newlist.append(entry)
line = line[idx+1:]
counter += 1
if "," not in line:
idx2 = line.find("\n")
newlist.append(line[:idx2])
nr_elements_per_line = int(len(newlist)/nr_of_lines)
tuple_list = []
for i in range(nr_of_lines):
tuple_list.append(tuple(newlist[nr_elements_per_line*i:nr_elements_per_line+i*nr_elements_per_line]))
return tuple_list
print(read_csv("example.csv"))