首先,到目前为止,我还在学习python和im,玩得很开心。在学习时遇到了这个问题,我有一个名为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'
发布于 2022-04-28 18:39:56
您需要将list对象转换为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提出的以下问题
发布于 2022-04-28 18:31:53
您需要使用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://stackoverflow.com/questions/72048624
复制相似问题