如何在 Python 中向 csv 文件添加标题?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15907200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:21:07  来源:igfitidea点击:

How to add a header to a csv file in Python?

pythoncsv

提问by Crolle

I've tried many solutions to add a header to my csv file, but nothing's working properly. Here they are :

我尝试了许多解决方案来向我的 csv 文件添加标题,但没有任何工作正常。他们来了 :

  1. I used the writerow method, but my data are overwriting the first row.

  2. I used the DictWriter method, but I don't know how to fill it correctly. Here is my code:

    csv = csv.DictWriter(open(directory +'/csv.csv', 'wt'), fieldnames = ["stuff1", "stuff2", "stuff3"], delimiter = ';')
    csv.writeheader(["stuff1", "stuff2", "stuff3"])
    
  1. 我使用了 writerow 方法,但我的数据覆盖了第一行。

  2. 我使用了 DictWriter 方法,但我不知道如何正确填充它。这是我的代码:

    csv = csv.DictWriter(open(directory +'/csv.csv', 'wt'), fieldnames = ["stuff1", "stuff2", "stuff3"], delimiter = ';')
    csv.writeheader(["stuff1", "stuff2", "stuff3"])
    

I got a "2 arguments instead of one" error and I really don't know why.

我收到了“2 个参数而不是一个”错误,我真的不知道为什么。

Any advice?

有什么建议吗?

采纳答案by Martijn Pieters

All you need to do is call DictWriter.writeheader()without arguments:

您需要做的就是DictWriter.writeheader()不带参数地调用:

with open(os.path.join(directory, 'csv.csv'), 'wb') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames = ["stuff1", "stuff2", "stuff3"], delimiter = ';')
    writer.writeheader()

You alreadytold DictWriter()what your headers are.

已经告诉DictWriter()了你的标题是什么。

回答by Rudresh Ajgaonkar

I encountered a similar problem when writing the CSV file. I had to read the csv file and modify some of the fields in it. To write the header in the CSV file, i used the following code:

我在写 CSV 文件时遇到了类似的问题。我不得不阅读 csv 文件并修改其中的一些字段。要在 CSV 文件中写入标题,我使用了以下代码:

reader = csv.DictReader(open(infile))
headers = reader.fieldnames

with open('ChartData.csv', 'wb') as outcsv:
    writer1 = csv.writer(outcsv)
    writer1.writerow(headers)

and when you write the data rows, you can use a DictWriter in the following way

并且在写入数据行时,可以通过以下方式使用 DictWriter

writer = csv.DictWriter(open("ChartData.csv", 'a' ), headers)

In the above code "a"stands for appending.

在上面的代码中,“a”代表附加.

In conclusion - > use ato appenddata to csv after you have written your header to the same file

总之->在标题写入同一文件后,使用a数据附加到 csv