以Python形式将标头添加到csv文件中

时间:2013-12-03 09:52:27

标签: python csv header

我写了一个合并两个csv文件的Python脚本,现在我想在最终的csv中添加一个标题。我尝试按照here报告的建议,但收到以下错误:expected string, float found。解决这个问题最灵活的方法是什么?

以下是我正在使用的代码:

import csv

with open('combined_file.csv', 'wb') as outcsv:
    writer = csv.DictWriter(outcsv, fieldnames = ["Date", "temperature 1", "Temperature 2"])
    writer.writeheader()

    with open('t1.csv', 'rb') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row + [0.0] for row in reader)

    with open('t2.csv', 'rb') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row[:1] + [0.0] + row[1:] for row in reader)

4 个答案:

答案 0 :(得分:80)

DictWriter()类需要每行词典。如果您只想写一个初始标题,请使用常规csv.writer()并为标题传入一个简单的行:

import csv

with open('combined_file.csv', 'wb') as outcsv:
    writer = csv.writer(outcsv)
    writer.writerow(["Date", "temperature 1", "Temperature 2"])

    with open('t1.csv', 'rb') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row + [0.0] for row in reader)

    with open('t2.csv', 'rb') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row[:1] + [0.0] + row[1:] for row in reader)

另一种方法是在复制数据时生成字典:

import csv

with open('combined_file.csv', 'wb') as outcsv:
    writer = csv.DictWriter(outcsv, fieldnames = ["Date", "temperature 1", "Temperature 2"])
    writer.writeheader()

    with open('t1.csv', 'rb') as incsv:
        reader = csv.reader(incsv)
        writer.writerows({'Date': row[0], 'temperature 1': row[1], 'temperature 2': 0.0} for row in reader)

    with open('t2.csv', 'rb') as incsv:
        reader = csv.reader(incsv)
        writer.writerows({'Date': row[0], 'temperature 1': 0.0, 'temperature 2': row[1]} for row in reader)

答案 1 :(得分:4)

在执行循环之前,您只需添加一行。这一行包含 您的CSV文件标题名称。

schema = ['a','b','c','b']
row = 4
generators = ['A','B','C','D']
with open('test.csv','wb') as csvfile:    
     writer = csv.writer(csvfile, delimiter=delimiter)
# Gives the header name row into csv
     writer.writerow([g for g in schema])   
#Data add in csv file       
     for x in xrange(rows):
         writer.writerow([g() for g in generators])

答案 2 :(得分:1)

这对我有用。

header = ['row1', 'row2', 'row3']
some_list = [1, 2, 3]
with open('test.csv', 'wt', newline ='') as file:
    writer = csv.writer(file, delimiter=',')
    writer.writerow(i for i in header)
    for j in some_list:
        writer.writerow(j)

答案 3 :(得分:0)

如果我们当时正在创建文件,那么这不是很简单,如果我们不向其附加数据,则只添加标头..

  conso_file_path = 'your_folder_path\your_file.csv'
    # Create File
    if not os.path.exists(conso_file_path):
        print("No File")
        header = ['col_name 1', 'col_name 1', 'col_name 3', 'col_name4']
        with open(conso_file_path, 'w') as f:
            writer = csv.writer(f)
            writer.writerow(header)