首页 > 解决方案 > 我将如何修改它以添加一列?

问题描述

我有 csv 文件。它没有列名。我需要在行首添加新列。我的意思是数组[0]。我是新来的。请帮我。

这是我拥有的 csv 文件

1,100,303,619,figure
338,162,143,423,text
85,768,554,39,text
504,164,24,238,subtitle

我只想像这样添加新列记录

Record_01,98,87,544,396,figure
Record_02,98,488,91,48,caption
Record_03,98,568,142,254,figure
Record_04,97,834,8,6,page

我试过这个代码它不起作用。它不显示错误消息。但这并没有改变任何东西。

key = []
for row, Record in enumerate(key):
    print('Record_{}'.format(row, Record))
    row.append(row[0])
    key.appen(row)
            with open('csvfiles', 'r') as csvinput:
                with open('csvfiles', 'w') as csvoutput:
                    writer = csv.writer(csvoutput, delimiter=',')
                    writer.writerow[key] 

非常感谢任何答案。

标签: pythonpython-3.xcsv

解决方案


根据您自己删除的答案,您已经很接近了。变化在于writer.writerows(data)您可以迭代行并更改每行以具有额外的条目,而不是您。

import csv
#load the file

with open('00001.csv') as input_file:
#read the input csv file 
    reader = csv.reader(input_file)
    data = [line for line in reader]
#load the the output file
with open('00001.csv','w') as output_file:
    writer = csv.writer(output_csvfile)
    #add the column name
    writer.writerow(["X", "Y", "Width", "Height", "Tag"])
    # for each line including indices
    for i,line in enumerate(data, start=1):
        # insert extra entry at beginning of line (index 0)
        line.insert(0,"Record_{}".format(i))
        # write the row.
        writer.writerow(line)

推荐阅读