2015-04-21 94 views
-3

我有一個列表在python中,我需要將輸出寫入csv。名單是:從python寫入文件到csv

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


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

我需要的輸出CSV爲:

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

我已經嘗試了一切,通過轉換爲字符串,等等...但我不能夠把它做..

這怎麼可能完成。謝謝

+2

請通過展示一些代碼,讓我們瞭解您已經嘗試過,最好的。 – helmbert

+2

http://stackoverflow.com/help/how-to-ask。堆棧溢出不是免費的代碼寫入服務。請告訴我們您的努力和實現的輸入,任何錯誤消息等。 –

+0

您的代碼不能正常工作? –

回答

1

您是否嘗試過使用join

lst = ["apricot", "banana", "cherry"] 
result = ",".join(lst) 
1

試試這個

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