Open In App

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

Last Updated : 11 Dec, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

A CSV file contains a tabular sort of data where each row contains comma-separated values. The columns may contain values belonging to different data structures. Python provides a wide range of methods and modules to carry out the interconversion of the CSV file to a pandas data frame and vice versa. A header of the CSV file is an array of values assigned to each of the columns. It acts as a row header for the data. Initially, the CSV file is converted to a data frame and then a header is added to the data frame. The contents of the data frame are again stored back into the CSV file. 

In this article, we are going to add a header to a CSV file in Python.

Method #1: Using header argument in to_csv() method.

Initially, create a header in the form of a list, and then add that header to the CSV file using to_csv() method.

The following CSV file gfg.csv is used for the operation:

Python3




# importing python package
import pandas as pd
  
# read contents of csv file
file = pd.read_csv("gfg.csv")
print("\nOriginal file:")
print(file)
  
# adding header
headerList = ['id', 'name', 'profession']
  
# converting data frame to csv
file.to_csv("gfg2.csv", header=headerList, index=False)
  
# display modified csv file
file2 = pd.read_csv("gfg2.csv")
print('\nModified file:')
print(file2)


Output: 

The CSV file gfg2.csv is created:

Method #2: Using DictWriter() method

Another approach of using DictWriter() can be used to append a header to the contents of a CSV file. The fieldnames attribute can be used to specify the header of the CSV file and the delimiter argument separates the values by the delimiter given in csv module is needed to carry out the addition of header. The writeheader() method is then invoked on csvwriter object, without passing any arguments.

Python3




# import required modules
import pandas as pd
import csv
  
# assign header columns
headerList = ['col1', 'col2', 'col3', 'col4']
  
# open CSV file and assign header
with open("gfg3.csv", 'w') as file:
    dw = csv.DictWriter(file, delimiter=','
                        fieldnames=headerList)
    dw.writeheader()
  
# display csv file
fileContent = pd.read_csv("gfg3.csv")
fileContent


Output:

The new CSV file gfg3.csv created is:

Note: This method is only applicable to empty CSV files.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads