Append a Header for CSV file?

2020-05-20 00:25发布

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

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

  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?

标签: python csv
5条回答
Lonely孤独者°
2楼-- · 2020-05-20 00:39

I know the question was asked a long time back. But for others stumbling across this question, here's an alternative to 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 -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.

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

sed 1i"ColA,ColB" mycsvfile.csv > newcsvfile.csv
查看更多
够拽才男人
3楼-- · 2020-05-20 00:40

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

 with open('mycsvfile.csv', 'a') as fd:
        reader = csv.DictReader(fd)
        reader.fieldnames = ["ColA" , "ColB"]
        for row in fd
查看更多
Juvenile、少年°
4楼-- · 2020-05-20 01:01

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

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 print statement will print to the file because of the inplace=True parameter.

查看更多
Evening l夕情丶
5楼-- · 2020-05-20 01:02

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:

#!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)
查看更多
兄弟一词,经得起流年.
6楼-- · 2020-05-20 01:04

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:

   from pandas import read_csv

   df = read_csv('test.csv')
   df.columns = ['a', 'b']
   df.to_csv('test_2.csv')
查看更多
登录 后发表回答