将标题行写入csv python

时间:2017-12-01 08:28:05

标签: python python-3.x csv selenium

如何在csv中向第一行添加标题?

我的解决方案目前附加了所有内容

类似于:writer.writerow(['DataA', 'DataB', 'DataC', 'DATA D'])[0]

我觉得有一种简单的方法可以做到这一点,而且我忽略了这一点。

我已经在网上看了很多例子,但我仍然在努力如何在csv中轻松完成这项工作。

作为一个例子,我想说我想刮掉SO的数据 - 加载硒,将其写入四列并执行20页。我希望每次都将标题写入第1行,然后附加已删除的数据

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)

1 个答案:

答案 0 :(得分:1)

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

检查出来:https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files