ItSolutionStuff.com

How to Add Header in CSV File using Python?

By Hardik Savani • October 30, 2023
Python

Hi Friends,

Today, how to add header in csv file using python is our main topic. This post will give you a simple example of create csv file with column names python. you will learn python add header to csv file. If you have a question about python add header to csv if not exists then I will give a simple example with a solution.

In this example, we will create demo.csv file with ID, Name and Email as header fields. we will create "data" list with values for write multiple rows to csv file. we will use open(), writer(), writerow(), writerows() and close() functions to create csv file from list.

writerow(): it will help to add header to csv file.

So, Without any further ado, let's see below code example:

You can use these examples with python3 (Python 3) version.

Example:

main.py

import csv
  
# open the file in the write mode
f = open('demo.csv', 'w')
  
# create the csv writer
writer = csv.writer(f)
  
header = ['ID', 'Name', 'Email']
data = [
	[1, 'Hardik Savani', 'hardik@gmail.com'],
	[2, 'Vimal Kashiyani', 'vimal@gmail.com'],
	[3, 'Harshad Pathak', 'harshad@gmail.com'],
]
  
# write the header
writer.writerow(header)
  
# write a row to the csv file
writer.writerows(data)
  
# close the file
f.close()

Output:

You can see csv file layout:

I hope it can help you...

Tags: Python
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Python Write CSV File from List Example

Read Now →

How to Create CSV File in Python?

Read Now →

How to Check If a List is Empty or Not in Python?

Read Now →

Python Read Text File into List Example

Read Now →

How to Read a Text File in Python?

Read Now →

Python Delete Folder and Files Recursively Example

Read Now →

Python Delete File if Exists Example

Read Now →

Python Post Request with Basic Authentication Example

Read Now →

Python Post Request with Bearer Token Example

Read Now →

Python Get File Extension from Filename Example

Read Now →

Python List All Dates Between Two Dates Example

Read Now →

Python POST Request with Parameters Example

Read Now →

How to Subtract Year to Date in Python?

Read Now →