简体   繁体   中英

Write list of list to csv in python

I have a function :

writer = csv.writer(open('dict.csv', 'ab'))
for row in izip_longest(finald, finalp, namebi, main):
    writer.writerow([x.encode("utf-8") for x in row])

finald , finalp and namebi are lists.

main is a list which has many other lists of same size.

I want to encode the data in utf-8 too. All the data in one row is related to each other so it can't go off sync.

I want csv output like :

finalp[0],finalp[0],namebi[0],main[0]key[0],main[0]key[1] .....

This should work:

for row in zip(finald, finalp, namebi, main):
    writer.writerow([x.encode("utf-8") for x in row[:-1]] +
                    [x.encode("utf-8") for x in row[-1]])

I use zip instead of izip_longest . The latter would need a fill values because the default None cannot be encoded and written to a file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM