How to add a header to a CSV file in Python?
Last Updated :
05 Apr, 2025
When you work with CSV files in Python, you might want to add a title row to make the data easier to read. A CSV file is like a table where each row is a piece of information, and each part of that information is separated by commas. By adding a title at the top, like "Name," "Age," and "Location," it helps you know what each column of the data means, making it easier to understand and use. Let's understand different methods to add a header to a CSV file.
Here’s what the gfg.csv file holds:
gfg.csv fileNote: A header causes a left shift only if its column count differs from the original data. If the header matches the columns, no shift occurs. Fewer columns result in a left shift, excluding extra ones, while more columns add new ones with missing values.
Using pandas
The pandas library simplifies CSV file operations. You can read a CSV file, update its columns with specified headers and save the modified file with ease. This method offers a high-level, easy-to-use approach and is efficient for larger datasets.
Python
import pandas as pd
# headers
h = ["ID", "Name", "Department"]
df = pd.read_csv("gfg.csv", header=None, names=h)
# Save the updated CSV file
df.to_csv("gfg_updated.csv", index=False)
Output

Explanation: pd.read_csv() load data from "gfg.csv" without headers (header=None). It then assigns the custom column names to the DataFrame using names=h. Finally, df.to_csv() saves the DataFrame to "gfg_updated.csv" without including the row indices (index=False).
Using csv module
The csv module is part of Python’s standard library, allowing you to read and write CSV files directly. This method involves reading the original file, writing the headers and then appending the data from the original file into the new one.
Python
import csv
# headers
h = ["ID", "Name", "Department"]
with open("gfg.csv", "r") as infile:
rows = infile.readlines()
with open("gfg_updated.csv", "w", newline='') as outfile:
writer = csv.writer(outfile)
writer.writerow(h) # Write headers
outfile.writelines(rows) # Write original data
Output

Explanation: This code reads all lines from the existing "gfg.csv" file and stores them in the rows variable. It then opens "gfg_updated.csv" in write mode, writes the custom headers and appends the original data from rows to the new file, resulting in a CSV with updated headers and unchanged data.
Using file handling
In this approach, you manually handle the file content by reading the original file and writing the updated file. You first add the headers, then append the existing content to the new file. This method provides more control but is more manual compared to using specialized libraries like pandas or csv.
Python
# header
h = "ID,Name,Department\n"
with open("gfg.csv", "r") as file:
content = file.read()
# Write header + existing content
with open("gfg_updated.csv", "w") as file:
file.write(header + content)
Output

Explanation: This code reads the content of "gfg.csv" into the content variable, then opens "gfg_updated.csv" in write mode, writing the custom header h followed by the original content. The result is a new CSV file with the specified header and the unchanged data from "gfg.csv".
Using shutil
The shutil library is useful for high-level file operations, such as moving or copying files. In this method, you rename (backup) the original file, create a new file with headers, and then copy the original content from the backup file. This method is useful if you want to keep the original file intact as a backup.
Python
import shutil
# header
h = "ID,Name,Department\n"
# Rename the original file
shutil.move("gfg.csv", "gfg_backup.csv")
# Write a new file with the header and content from the backup
with open("gfg.csv", "w") as new_file:
new_file.write(header)
with open("gfg_backup.csv", "r") as old_file:
new_file.write(old_file.read())
Output
Backup csv file
Updated csv fileExplanation: This code renames "gfg.csv" to "gfg_backup.csv", creating a backup. It then creates a new "gfg.csv" file, writes the custom header to it, and appends the content from the backup file, resulting in a new "gfg.csv" with the header and original data.
Similar Reads
How to add timestamp to CSV file in Python Prerequisite: Datetime module In this example, we will learn How to add timestamp to CSV files in Python. We can easily add timestamp to CSV files with the help of datetime module of python. Let's the stepwise implementation for adding timestamp to CSV files in Python. Creating CSV and adding timest
5 min read
How to delete a CSV file in Python? In this article, we are going to delete a CSV file in Python. CSV (Comma-separated values file) is the most commonly used file format to handle tabular data. The data values are separated by, (comma). The first line gives the names of the columns and after the next line the values of each column. Ap
2 min read
How to add header row to a Pandas Dataframe? A header necessarily stores the names or headings for each of the columns. It helps the user to identify the role of the respective column in the data frame. The top row containing column names is called the header row of the data frame. There are two approaches to add header row to a Pandas Datafra
4 min read
How to Sort data by Column in a CSV File in Python ? In this article, we will discuss how to sort CSV by column(s) using Python. Method 1: Using sort_values() We can take the header name as per our requirement, the axis can be either 0 or 1, where 0 means 'rows' and '1' means 'column'. Ascending can be either True/False and if True, it gets arranged i
3 min read
How to save a Python Dictionary to a CSV File? CSV (Comma-Separated Values) files are a popular format for storing tabular data in a simple, text-based format. They are widely used for data exchange between applications such as Microsoft Excel, Google Sheets and databases. In this article, we will explore different ways to save a Python dictiona
4 min read
How to read csv file with Pandas without header? Prerequisites: Pandas 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. This article discusses how we can read a csv file without header using pandas. To do this header attribute should be set to None while reading the file. Syntax:
1 min read