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
import pandas as pd
file = pd.read_csv( "gfg.csv" )
print ( "\nOriginal file:" )
print ( file )
headerList = [ 'id' , 'name' , 'profession' ]
file .to_csv( "gfg2.csv" , header = headerList, index = False )
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 pandas as pd
import csv
headerList = [ 'col1' , 'col2' , 'col3' , 'col4' ]
with open ( "gfg3.csv" , 'w' ) as file :
dw = csv.DictWriter( file , delimiter = ',' ,
fieldnames = headerList)
dw.writeheader()
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.