Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export all values of lists to csv on Python

list_1 = ['1','2','3','4','5','6','7','8']
list_2 = ['n1','n2','n3','n4','n5','n6','n7','n8','n9','n10']
list_3 = ['o1','o2','o3','o4','o5','o6','o7','o8','o9','o10']

cols = zip(list_1,list_2,list_3)

with open('file.csv', 'w', newline='') as f:
    thewriter = csv.writer(f)

    thewriter.writerow(['list_1','list_2','list_3'])
    for col in cols:
       thewriter.writerow(col)

Output

list1   list2   list3
  1      n1      o1
  2      n2      o2
  3      n3      o3
  4      n4      o4
  5      n5      o5
  6      n6      o6
  7      n7      o7
  8      n8      o8

Expected Output

list1   list2   list3
  1      n1      o1
  2      n2      o2
  3      n3      o3
  4      n4      o4
  5      n5      o5
  6      n6      o6
  7      n7      o7
  8      n8      o8
         n9      o9
         n10     o10 

I have 3 lists, list_1 has 8 items, list_2 has 10 items and list_3 also have 10 items,

but when I write the lists to csv, list_2 and list_3 columns do not show the last 2 items.

like image 346
Victor Avatar asked Jan 25 '23 03:01

Victor


1 Answers

It's the default behavior of zip: truncate to the length of the shortest iterable. You can use zip_longest instead:

  • Import it first:
from itertools import zip_longest
  • Then replace the line where you assign cols with:
cols = zip_longest(list_1,list_2,list_3, fillvalue="")
like image 74
RMPR Avatar answered Jan 30 '23 00:01

RMPR