首先,我還在學習 python,到目前為止我玩得很開心。在學習時我遇到了這個問題,我有一個名為 MyList 的變數,如下所示
MyList = [{'orange', 'Lemon'},
{'Apple', 'Banana', 'orange', 'Lemon'},
{'Banana', 'Lemon'},
{'Apple', 'orange'}]
我想以與上面相同的順序將串列轉儲到 csv 檔案中的行中,因此 csv 將如下所示:
orange Lemon
Apple Banana orange Lemon
Banana Lemon
Apple orange
所以我把命令放在下面
MyList.to_csv("MyList.csv", sep='\t', encoding='utf-8')
但是它給了我以下錯誤
AttributeError: 'list' object has no attribute 'to_csv'
uj5u.com熱心網友回復:
您需要將串列物件轉換為 csv 物件。
import csv
with open('MyList.csv', 'w', newline='') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerows(MyList)
請參閱Fortilan 的以下問題Create a .csv file with values from a Python list
uj5u.com熱心網友回復:
您需要使用該csv模塊并打開一個檔案進行寫入:
import csv
MyList = [{'orange', 'Lemon'},
{'Apple', 'Banana', 'orange', 'Lemon'},
{'Banana', 'Lemon'},
{'Apple', 'orange'}]
with open('MyList.csv', 'w') as f:
# using csv.writer method from csv module
write = csv.writer(f)
write.writerows(MyList)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/466919.html
上一篇:在復雜的列上使用pandas地圖
