Open In App

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

Last Updated : 05 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

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

Updated_csv

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

Updated_csv

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

Updated_csv

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

Backup csv file

Updated_csv

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.



Next Article
Practice Tags :

Similar Reads