Python 为 CSV 文件附加标题?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28162358/
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-19 02:49:52  来源:igfitidea点击:

Append a Header for CSV file?

pythoncsv

提问by Sakil Chowdhury

I am trying to add a header to my CSV file.

我正在尝试向我的 CSV 文件添加标题。

I am importing data from a .csv file which has two columns of data, each containing float numbers. Example:

我正在从一个 .csv 文件导入数据,该文件有两列数据,每一列都包含浮点数。例子:

  11   22
  33   44
  55   66

Now I want to add a header for both columns like:

现在我想为两列添加一个标题,如:

 ColA  ColB
  11    22
  33    44
  55    66

I have tried this:

我试过这个:

with open('mycsvfile.csv', 'a') as f:
    writer = csv.writer(f)
    writer.writerow(('ColA', 'ColB'))

I used 'a'to append the data, but this added the values in the bottom row of the file instead of the first row. Is there any way I can fix it?

我曾经'a'追加数据,但这会在文件的底行而不是第一行中添加值。有什么办法可以解决吗?

采纳答案by Mark Tolonen

One way is to read all the data in, then overwrite the file with the header and write the data out again. This might not be practical with a large CSV file:

一种方法是读入所有数据,然后用头覆盖文件并再次写出数据。对于大型 CSV 文件,这可能不切实际:

#!python3
import csv
with open('file.csv',newline='') as f:
    r = csv.reader(f)
    data = [line for line in r]
with open('file.csv','w',newline='') as f:
    w = csv.writer(f)
    w.writerow(['ColA','ColB'])
    w.writerows(data)

回答by adrianX

i think you should use pandas to read the csv file, insert the column headers/labels, and emit out the new csv file. assuming your csv file is comma-delimited. something like this should work:

我认为您应该使用 Pandas 来读取 csv 文件,插入列标题/标签,并发出新的 csv 文件。假设您的 csv 文件以逗号分隔。这样的事情应该工作:

   from pandas import read_csv

   df = read_csv('test.csv')
   df.columns = ['a', 'b']
   df.to_csv('test_2.csv')

回答by Hai Vu

In this case, You don't need the CSV module. You need the fileinputmodule as it allows in-place editing:

在这种情况下,您不需要 CSV 模块。您需要该fileinput模块,因为它允许就地编辑:

import fileinput

for line in fileinput.input(files=['mycsvfile.csv'], inplace=True):
    if fileinput.isfirstline():
        print 'ColA,ColB'
    print line,

In the above code, the printstatement will print to the file because of the inplace=Trueparameter.

在上面的代码中,print由于inplace=True参数的原因,语句将打印到文件中。

回答by Ketan Goyani

You can set reader.fieldnames in your code as list like in your case

您可以将代码中的 reader.fieldnames 设置为列表,就像您的情况一样

 with open('mycsvfile.csv', 'a') as fd:
        reader = csv.DictReader(fd)
        reader.fieldnames = ["ColA" , "ColB"]
        for row in fd

回答by Mishal Ahmed

I know the question was asked a long time back. But for others stumbling across this question, here's an alternative to Python.

我知道这个问题很久以前就被问到了。但是对于其他遇到这个问题的人来说,这里有一个 Python 的替代方案。

If you have access to sed (you do if you are working on Linux or Mac; you can also download Ubuntu Bash on Windows 10 and sed will come with it), you can use this one-liner:

如果您有权访问 sed(如果您在 Linux 或 Mac 上工作,则可以访问;您还可以在 Windows 10 上下载 Ubuntu Bash,sed 将随附),您可以使用以下单行:

sed -i 1i"ColA,ColB" mycsvfile.csv

The -i will ensure that sed will edit in-place, which means sed will overwrite the file with the header at the top. This is risky.

-i 将确保 sed 将就地编辑,这意味着 sed 将覆盖带有顶部标题的文件。这是有风险的。

If you want to create a new file instead, do this

如果您想创建一个新文件,请执行以下操作

sed 1i"ColA,ColB" mycsvfile.csv > newcsvfile.csv