-3

I have a list in python and i need to write the output to csv. list is :

>>>final_name[0] 
[['Serbs'], ['Joachim RA'], [''], ['Mr RA'], [''], ['Albanian'], ['Boris Tadic', 'Serbia']]


>>> final_name[1]
 [['Philippine', 'Gloria Macapagal Arroyo', 'Mitag'], ['Anthony Golez'], ['Golez'], [''], ['Golez'], ['']]

I need the output in csv as:

1 Serbs,Joachim RA,Mr RA,Albanian,...
2 Philippine,Gloria Macapagal,...  

I have tried everything, by converting to string,etc...but i am not able to get it done..

How could this be done. thank you

user2876812
  • 316
  • 1
  • 4
  • 15
  • 2
    Please show us what you have already tried, best by showing some code. – helmbert Apr 21 '15 at 12:19
  • 2
    http://stackoverflow.com/help/how-to-ask. Stack Overflow is not a free code-writing service. Please show us your efforts and achieved input, any error messages etc. – Łukasz Rogalski Apr 21 '15 at 12:21
  • In what way is your code not working? – Peter Wood Apr 21 '15 at 12:32
  • as a hint to help you learn - you'll need enumerate() and print() and a little bit of string manipulation. throw in a couple of constructs like for ... in loop and if-else and you'll get there :) – mkathuri Apr 21 '15 at 12:32
  • possible duplicate of [Create a .csv file with values from a Python list](http://stackoverflow.com/questions/2084069/create-a-csv-file-with-values-from-a-python-list) – Henrik Apr 21 '15 at 12:32
  • also possible duplicate of http://stackoverflow.com/questions/14037540/writing-a-python-list-of-lists-to-a-csv-file – Henrik Apr 21 '15 at 12:33

2 Answers2

1

Have you tried to use join?

lst = ["apricot", "banana", "cherry"]
result = ",".join(lst)
Tolokoban
  • 2,017
  • 11
  • 17
1

Try this

with open('test.csv', 'wb') as csvfile:
    for i,j in enumerate(final_name, 1):
        to_write = [item for sublist in j for item in sublist if item]
        spamwriter = csv.writer(csvfile, delimiter=',')
        spamwriter.writerow([i]+to_write)

$ cat test.csv
1,Serbs,Joachim RA,Mr RA,Albanian,Boris Tadic,Serbia
2,Philippine,Gloria Macapagal Arroyo,Mitag,Anthony Golez,Golez,Golez
itzMEonTV
  • 17,660
  • 3
  • 31
  • 40