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 file
Note: 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 file
Explanation: 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 timestamp to excel file in Python
In this article, we will discuss how to add a timestamp to an excel file using Python. Modules requireddatetime: This module helps us to work with dates and times in Python.pip install datetimeopenpyxl: It is a Python library used for reading and writing Excel files.pip install openpyxltime: This mo
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 plot Bar Graph in Python using CSV file?
CSV stands for "comma separated values", that means the values are distinguished by putting commas and newline characters. A CSV file provides a table like format that can be read by almost every spreadsheet reader like Microsoft Excel and Google Spreadsheet. A Bar Graph uses labels and values where
2 min read
How to read all CSV files in a folder in Pandas?
Our task is to read all CSV files in a folder into single Pandas dataframe. The task can be performed by first finding all CSV files in a particular folder using glob() method and then reading the file by using pandas.read_csv() method and then displaying the content. ApproachImport Required Librari
2 min read
How To Read .Data Files In Python?
Unlocking the secrets of reading .data files in Python involves navigating through diverse structures. In this article, we will unravel the mysteries of reading .data files in Python through four distinct approaches. Understanding the structure of .data files is essential, as their format may vary w
4 min read
How to Add a Column to a MySQL Table in Python?
Prerequisite: Python: MySQL Create Table Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database. ALTER statement
4 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