Jay Park
Jay Park

Reputation: 348

How to add a header for a CSV file

Currently I have a CSV file, it just only has 1 attribute at the first row. So, it can not be the header for this csv file. Then I re-write a new file to generate a new CSV file. The data format of this CSV file is like the screenshot below. It contains 5 columns - I would like to add column1 and column2, column3, column4, column5 as the headers for this CSV file.

enter image description here

I tried to use panda to give a header to this csv file but it does not work at all. Here is my code to add a header for this csv file.

with open("ex_fts.csv",'r') as f:
    with open("updated_test.csv",'w') as f1:
        next(f) # skip header line
        for line in f:
            f1.write(line)
a = df.to_csv("updated_test.csv", header=["Letter", "Number", "Symbol","a","as"], index=False)
print(a)

Upvotes: 1

Views: 3611

Answers (2)

cisco
cisco

Reputation: 888

Just write the header before writing each row

columnNames = ["Letter", "Number", "Symbol", "a", "as"]

with open("ex_fts.csv",'r') as f:
    with open("updated_test.csv",'w') as f1:
        # Write new header
        f1.write(','.join(columnNames) + '\n') 

        next(f) # skip header line
        for line in f:
            f1.write(line)

Upvotes: 1

norie
norie

Reputation: 9857

There appears to be 6 columns in your data, so I've used generic names for the header - replace them with the real column names.

import pandas as pd

header = ','.join(["Column1", "Column2", "Column3", "Column4", "Column5", "Column6"])

with open("ex_fts.csv",'r') as f:
    with open("updated_test.csv",'w') as f1:
        f1.write(header+'\n')
        for line in f:
            data = line.replace('\t', ',')

            f1.write(data)

df = pd.read_csv('updated_test.csv',index_col=None)

print(df)

Upvotes: 2

Related Questions