[英]Making every element of a list part of a CSV header
I have a list: 我有一个清单:
[cat, dog, mouse]
and I wish for all the list items to be headers in a csv file like this: 我希望所有列表项都像这样的csv文件中的标头:
cat,dog,mouse
data,data,data
date,data,data
I have the following code to open a file, but I am not sure how to assign the animals to the headers: 我有以下代码打开文件,但不确定如何将动物分配给标题:
with open(fname, 'w') as my_csv:
my_csv.write(#cat,dog,mouse needs to go in here)
csv_writer = csv.writer(my_csv, delimiter=',')
I don't want to explicitly write cat,dog,mouse
as these animals can change due to user input choosing the animals further up the code. 我不想显式地编写cat,dog,mouse
因为这些动物可能会由于用户输入而在代码上方进一步选择动物而改变。
I think the best way to do this would be to use csv.DictWriter
. 我认为做到这一点的最佳方法是使用csv.DictWriter
。 Here's an example with your problem: 这是您的问题的示例:
import csv
with open('names.csv', 'w') as csvfile:
fieldnames = ['Cat', 'Dog', 'Mouse']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'Cat': 'Data', 'Dog': 'Data', 'Mouse': 'Data'})
Just join the elements by ,
and then write it on the csv file. 只需通过将元素连接起来,
然后将其写入csv文件即可。
li = ['cat', 'dog', 'mouse']
with open(fname, 'w') as my_csv:
my_csv.write(','.join(li))
csv_writer = csv.writer(my_csv, delimiter=',')
Just write the list as the first row. 只需将列表写为第一行。 Also note that the file should be opened with newline=''
in Python 3 or 'wb'
in Python 2 for correct handling of newlines on all OSs: 另请注意,在所有OS上正确处理换行符时,应在Python 3中使用newline=''
或在Python 2中使用'wb'
打开文件:
li = ['cat', 'dog', 'mouse']
with open(fname, 'w', newline='') as my_csv:
csv_writer = csv.writer(my_csv, delimiter=',')
csv_writer.writerow(li)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.