I’ve come up with two different functions for this exercise. One using the csv class writer and one with the DictWriter class. Both pass the expected results listed but, they fail the private test cases?
import csv
def csvWriter(filename, records):
header = []
for i in records:
if len(i) < 1:
records.remove(i)
for i in records:
for v in i:
if v not in header:
header.append(v)
for i in records:
if len(i) == 0:
return '0 records processed.'
test=open(filename,'w')
wr = csv.writer(test,header,lineterminator='\n')
wr.writerow(header)
for i in records:
wr.writerow(i.values())
test.close()
return '%d records processed.' % len(records)
csvWriter(‘filename’,[{‘a’:1,’b’:2},{‘a’:3,’b’:4}]
repr(open(‘filename’).read()) —> ‘a,b\n1,2,\na,b\n3,4’ check
‘2 records passed.’ —> ‘2 records passed.’ check
Private Test Cases —> Failed ?
The reason this function was failing on the Private Test Cases was, that a second argument could be passed and the values would be written without being sorted.
Still pretty rough, we weren’t suppose to use the csv module either. I’m going go back to improve upon this and give it a try without the module.
Any suggestions?