-2

I have the follwing lists an I want to store them in the csv example bellow. Can you help? I have seen relevant post but the obtained csv is not what I want. I past the output since now accoring to the afforementioned post.

list1 = ['str1', 'str2','str3']
list2 = ['str1']
list3 = ['str1', 'str2']
lists.append(list1)
lists.append(list2)
lists.append(list3) 

for l in lists:
   '''save each list in a csv row where each element of the 
      list will be stored in separete cell.'''

CSV example:

     cell1 cell2 cell3 
row1  str1 str2 str3
row2  str1
row3  str1 str2

CSV undesired(place all strings in the first cell):

      cell1          cell2 cell3 
row1  str1 str2 str3
row2  str1
row3  str1 str2 
Community
  • 1
  • 1
Thoth
  • 929
  • 12
  • 31
  • Could you elaborate on: "For each row of the csv the strings of the specific list will be stored in a cell", please? Perhaps give an example, because it is quite confusing - as read from what you have, it seems as though you've mistaken cells with rows? – jrd1 May 27 '14 at 13:16

2 Answers2

1

With csv library:

import csv

with open('your_file.csv', 'wb') as csv_file: 
   csv_writer = csv.writer(csv_file, delimiter=";")
   for l in lists:
        csv_writer.writerow(l)
Sébastien Deprez
  • 4,433
  • 1
  • 23
  • 33
  • I think instead of `reader` writter is needed. Also all the strings from all the lists are stored in the first collumn. – Thoth May 27 '14 at 13:52
  • Yes writer indeed. Updated the answer. By default, it separates string by a comma ",", the strings are not in the same column. You can set another delimiter if you want to. – Sébastien Deprez May 27 '14 at 14:36
1

Or just this way :

file = open("newfile.csv", "w")
sep = ";"    # your favorite separator
for l in list :
    for e in l :
        file.write (e + sep)
    file.write ("\n")
Louis
  • 2,790
  • 1
  • 17
  • 23