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:
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.
The new CSV file gfg3.csv created is:
Note: This method is only applicable to empty CSV files.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.