Skip to content
Advertisement

Using Python writerows with list of lists error

I’m trying to write a csv file using pythons CSV library. So here’s my actual code:

import csv

dummy_csv_list = [
    ['title1','title2','title3','title4'],
    ['simedata', 'otherdata','somethingelse','yadayada'],
    ['something','','preivous is empty','gotyou"doublequotes']
]

csvfile = StringIO()
writer = csv.DictWriter(csvfile, fieldnames=csv_list[0], dialect='excel')
writer.writeheader()
writer.writerows(csv_list[1:])

However I get this error when I run it:

Traceback (most recent call last): File “”, line 1, in File “/home/jean/dev/myproj/myproj/utils.py”, line 130, in test_mail writer.writerows(csv_list[1:]) File “/usr/lib/python3.8/csv.py”, line 157, in writerows return self.writer.writerows(map(self._dict_to_list, rowdicts)) File “/usr/lib/python3.8/csv.py”, line 147, in _dict_to_list wrong_fields = rowdict.keys() – self.fieldnames AttributeError: ‘list’ object has no attribute ‘keys’

Is it expecting a dict instead of a list? Wasnt it supposed to receive a list (rows) of lists (fields) to write the csv file?

Any input is appreciated! thanks

Advertisement

Answer

Yes it is expecting a dict.

I hope my version can help you.

import csv

dummy_csv_list = [
    ['title1', 'title2', 'title3', 'title4'],
    ['simedata', 'otherdata', 'somethingelse', 'yadayada'],
    ['something', '', 'preivous is empty', 'gotyou"doublequotes']
]

csvfile = open("test.csv", "w", newline="")
writer = csv.DictWriter(csvfile, fieldnames=dummy_csv_list[0], dialect='excel')
writer.writeheader()

for row in dummy_csv_list[1:]:
    writer.writerow(
        {dummy_csv_list[0][0]: row[0], dummy_csv_list[0][1]: row[1], dummy_csv_list[0][2]: row[2], dummy_csv_list[0][3]: row[3]})
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement