add headers to a csv file using python

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

In this tutorial, we’ll try to understand how to add a header in a csv file using Python with the help of some examples.

In simple terms, a csv file contains tabular data with comma-separated values in each row. A row header, here, represents an additional row at the top indicating the column names.

You can use the following methods to add a header to a csv file using Python –

  1. Using the pandas dataframe to_csv() method.
  2. Using the csv module in Python.

Let’s now look at the above methods in detail. We’ll work with a csv file without a header to demonstrate the examples. This is how the csv file looks.

the csv file contents without any headers

Using the pandas dataframe to_csv() method

Steps to add a header to a csv file using the pandas.DataFrame.to_csv() method are.

  • Import the pandas module.
  • Read the csv file as a pandas DataFrame object (pass header=None as an additional parameter).
  • Save the dataframe as a csv file (along with the specified header) by using the pandas dataframe to_csv() method.

Now, let us try to understand the above method, with some worked out examples.

import pandas as pd

# read the csv file as a dataframe
df = pd.read_csv("students.csv", header=None)

# display the dataframe
print(df)

Output:

    0      1       2
0  14   Tony    Male
1  15   Emma  Female
2  14  Rishi    Male
3  16   Zara  Female

We are reading the csv file with the pandas read_csv() function and pass header=None because we know that the csv file doesn’t have any headers. If we do not pass header=None, the function will infer the header by itself and since this file doesn’t have a header, it will use the first row as the header (which we do not want).

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

You can see that the dataframe doesn’t have any headers.

Let’s save this dataframe as a csv file with a header. For this, use the pandas.DataFrame.to_csv() function and pass the header values as a list to the header parameter.

# header values for the data 
header_ls = ['Age', 'Name', 'Gender']
# save dataframe as a csv file with the given headers
df.to_csv("students_updated.csv", header=header_ls, index=False)

Here, we saved our csv file with the headers as “students_updated.csv”. Also note that here, we are using index=False to not add a separate column for the dataframe index in the csv file.

If we look at the contents of the csv file, you’ll see that the header is present.

the resulting csv file with the headers added

The same can be confirmed by reading the csv file as a dataframe.

# read the updated csv file as dataframe
df2 = pd.read_csv("students_updated.csv")
# display the dataframe
print(df2)

Output:

   Age   Name  Gender
0   14   Tony    Male
1   15   Emma  Female
2   14  Rishi    Male
3   16   Zara  Female

The header is present.

Using the csv module

Alternatively, you can use the csv module, which is a built-in Python library that lets you work with csv files. Use the following steps to add a header using the csv module.

  1. Import the csv module.
  2. Read the contents of the csv file using the csv.reader() method and convert it to a list.
  3. Add the headers to use as the first row in the above list.
  4. Save the above list as a csv file using the csv.writer() method.

Let’s take the same example as above and use the “students.csv” file which does not have a header.

import csv

# read the csv file
with open("students.csv", "r") as csv_file:
    # read the contents of the file
    reader = csv.reader(csv_file)
    # convert to list
    data = list(reader)

# add the header to the list created above
header_ls = ["Age", "Name", "Gender"]
data.insert(0, header_ls)

# write the data to a csv file
with open("students_updated2.csv", "w") as csv_file:
    # writer object
    writer = csv.writer(csv_file)
    # write data to the csv file
    writer.writerows(data)

If you now check the contents of the “students_updated2.csv” file, it’ll have the given header.

the resulting csv file with the headers added

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Authors

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

  • Chaitanya Betha

    I'm an undergrad student at IIT Madras interested in exploring new technologies. I have worked on various projects related to Data science, Machine learning & Neural Networks, including image classification using Convolutional Neural Networks, Stock prediction using Recurrent Neural Networks, and many more machine learning model training. I write blog articles in which I would try to provide a complete guide on a particular topic and try to cover as many different examples as possible with all the edge cases to understand the topic better and have a complete glance over the topic.

Scroll to Top