将标头行写入csv python [英] write header rows to csv python
问题描述
如何在csv中的第一行添加标题?
How do I add headers to row one in a csv?
我的解决方案当前会附加所有内容
My solution currently appends everything
类似的东西: writer.writerow(['DataA','DataB','DataC','DATA D'])[0]
我觉得这里有一个简单的方法,而我却忽略了显而易见的方法.
I feel like there an easy way of doing this and I'm overlooking the obvious.
我在网上查看了很多示例,但仍在为如何轻松地在csv中执行此操作而苦苦挣扎.
I've looked at a lot of examples online but am still struggling as to how you can easily do this in a csv.
作为一个例子,我想抓取SO的数据-加载硒,将其写入四列,然后进行20页.我想每次都将标头写入第1行,然后附加所抓取的数据
As an example lets say I wanted to scrape data of SO - load up selenium, write that into four columns and do this for 20 pages. I'd want to write the headers to row 1 each time and then append the scraped data
with open('C:\\fa.csv', 'a+', newline='', encoding="utf-8") as outfile:
writer = csv.writer(outfile)
writer.writerow(['DataA', 'DataB', 'DataC', 'DataD'])
for row in zip(ZAW_text, RESULTS1, RESULTS):
writer.writerow(row)
#writer.writerows({'Date': row[0], 'temperature 1': row[1], 'temperature 2': 0.0} for row in writer)
print(row)
推荐答案
import csv
import os
file_name = 'C:\\fa.csv'
fake_data = [[1, 2, 3, 4, 5, 4444, 6, 67], [1, 2, 3, 4, 5, 4444, 6, 67],
[1, 2, 3, 4, 5, 4444, 6, 67], [1, 2, 3, 4, 5, 4444, 6, 67]]
headers = ['DataA', 'DataB', 'DataC', 'DataD']
if os.path.isfile(file_name):
with open(file_name, 'a', encoding="utf-8") as outfile:
writer = csv.writer(outfile)
for datum in fake_data:
writer.writerow(datum)
else:
with open(file_name, 'w', encoding="utf-8") as outfile:
writer = csv.writer(outfile)
writer.writerow(headers)
for datum in fake_data:
writer.writerow(datum)
在第一行 open('C:\\ fa.csv','a +',newline ='',encoding ="utf-8")
中,您有 a +
是附加,而您要 w
是写的.
In the first line open('C:\\fa.csv', 'a+', newline='', encoding="utf-8")
you have a+
which is append you want w
which is write.
检查以下内容: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
这篇关于将标头行写入csv python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!