如何在python中用列标题在csv文件的每一行中写入数据

2024-09-30 04:38:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在csv文件的每一行中写入数据,而不覆盖,但要有一个标题列。有了这段代码,我可以写文件中每一行的数据,但也可以写头。我希望头也在列的顶部,然后在每个raw中写入数据。这是我使用的代码

import csv
c =csv.writer(open("C:/Config/Output/box.csv","ab"), lineterminator='\n')
c.writerow(['ColA','ColB'])
c.writerow([dfl_origin[0],dfl_origin[1]])

dfl\u origin[0]和dfl\u origin[1]是变量。你知道吗

好的,这是更多的代码

def calculate_doorframe_parameters(subfeature_dict):
    global dfl_hor_thr , dfl_ver_thr
    global dfl_origin
    dfl_points_dict = {}

    for subfeature in subfeature_dict:
        if ("doorframelines" in subfeature):
            dfl_points_dict[subfeature] = subfeature_dict[subfeature]

    if len(dfl_points_dict) == 2: #Invalid Case for algorithm (Can be removed after confirmation)
        dfl_hor_thr =  abs(dfl_points_dict['doorframelines1'][0] - dfl_points_dict['doorframelines2'][0])

    if len(dfl_points_dict) == 6:
        dfl_hor_thr = abs(dfl_points_dict['doorframelines2'][0] - dfl_points_dict['doorframelines5'][0])
        dfl_ver_thr =  abs(dfl_points_dict['doorframelines6'][1] - dfl_points_dict['doorframelines4'][1])

        #Find Origin of DoorFrame
        dfl_origin_X = min([dfl_points_dict['doorframelines2'][0], dfl_points_dict['doorframelines5'][0],dfl_points_dict['doorframelines1'][0] , dfl_points_dict['doorframelines3'][0]])
        dfl_origin_Y = min([dfl_points_dict['doorframelines2'][1], dfl_points_dict['doorframelines5'][1],dfl_points_dict['doorframelines1'][1] , dfl_points_dict['doorframelines3'][1]])
        dfl_origin= [dfl_origin_X,dfl_origin_Y]
        import csv
        c =csv.writer(open("C:/Config/Output/box2.csv","ab"), lineterminator='\n')
        c.writerow(['ColA ColB'])
        c.writerow([dfl_origin[0],dfl_origin[1]])

这就是结果

ColA, ColB
1033  87.0
ColA  ColB
987   65.0

预期结果应该是

    ColA, ColB
    1033  87.0
    987   65.0

有什么帮助吗?你知道吗


Tags: csv数据代码iforigindictpointscolb
1条回答
网友
1楼 · 发布于 2024-09-30 04:38:52

你可以用这样的东西

with open('names.csv', 'a') as csvfile:

    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})

“a”代表“append”解决覆盖问题

更多信息: https://docs.python.org/2/library/csv.html

相关问题 更多 >

    热门问题