【问题标题】:how would I modify this to add a column? [duplicate]我将如何修改它以添加一列? [复制]
【发布时间】:2020-07-16 09:38:25
【问题描述】:

我有 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] 

非常感谢任何答案。

【问题讨论】:

  • 我没有得到任何答案,这次我只问一个问题。如果你能提供代码非常感谢
  • 如果你能提供代码:你不想要答案,你希望有人为你写一个工作代码。

标签: python python-3.x csv


【解决方案1】:

根据您自己删除的答案,您非常接近。变化在于,您可以遍历行并更改每一行以拥有一个额外的条目,而不是 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)

【讨论】:

    【解决方案2】:

    对于那些可能遇到此类问题的人,我找到了答案。 没有办法单独添加标题。您必须重新编写整个 csv 文件。此代码可能会对您有所帮助。

    import csv
    #load the file
    
    with open('00001.csv', newline='') 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',newline='') as output_file:
        writer = csv.writer(output_csvfile)
        #add the column name
        writer.writerow(["X", "Y", "Width", "Height", "Tag"])
        writer.writerows(data)
    

    【讨论】:

    • 你很幸运,我有足够的代表在它被删除时看到它,如果你发布了这个代码和一个问题,比如“我将如何修改它以添加一个列?”可能会有更好的接收,至少有更多人评论“writerows 写入所有数据,您需要修改数据”
    • @TadhgMcDonald-Jensen 你是对的。我没有任何想法。这是我的坏事。我应该选择正确的关键字。非常感谢您指出。下次我会更小心的。
    • 别担心!我完全明白入门是多么具有挑战性,我坚信看到对您已经理解的代码进行微小更改的示例对于学习如何操作您可能在其他问题或文档中看到的示例非常有帮助。而且还没有那种经验寻求帮助是非常困难的。就目前而言,您的问题非常好,您有样本输入,预期输出,意图非常明确,尝试就在那里,给出了实际行为。你有所有正确的元素!
    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2016-12-12
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    相关资源
    最近更新 更多