ItSolutionStuff.com

How to Create CSV File in Python?

By Hardik Savani • October 30, 2023
Python

Hi Artisan,

This detailed guide will cover how to create csv file in python. I am going to show you about python create csv file example. I would like to share with you python writing csv file example. This article will give you a simple example of python output to csv file example. Alright, let us dive into the details.

In this example, we will create demo.csv file with ID, Name and Email fields. we will use open(), writer(), writerow(), writerows() and close() functions to create csv file. we will use functions for the following reasons.

open(): it will create csv file if not exist.

writer(): it will create csv file object for write new rows.

writerow(): it will write single row with heading.

writerows(): it will write multiple rows with list.

close(): it will close created new csv file object.

Now, you can see below simple code and output:

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

How to Read Text File Line by Line in Python?

Read Now →

How to Append Text or Lines to a Text File in Python?

Read Now →

Python Create Text File If Not Exists Example

Read Now →

How to Reverse List Elements in Python?

Read Now →

Python Create an Empty Text File Example

Read Now →

Python List Add Element at Beginning Example

Read Now →

Python List Print All Elements Except First Example

Read Now →

How to Get Max Value from Python List?

Read Now →

Python Get First Date of Last Month Example

Read Now →

How to Add Minutes to DateTime in Python?

Read Now →

Python POST Request with Parameters Example

Read Now →

Python GET Request with Parameters Example

Read Now →

Python Get Day Name from Number Example

Read Now →