ItSolutionStuff.com

How to Write CSV File in Python?

By Hardik Savani • October 30, 2023
Python

Hey Dev,

This tutorial will give you an example of how to write csv file in python. you can see python write csv file example. you'll learn python writing csv file example. Here you will learn python output to csv file example. Let's get started with how to write csv file in python 3.

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

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

writer(): it will write 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 Write Multiple Rows in CSV using Python?

Read Now →

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

Read Now →

How to Get Unique Elements from List in Python?

Read Now →

Python List Remove Element by Index Example

Read Now →

Python Delete Files with Specific Extension Example

Read Now →

Python Copy File From one Directory to Another Example

Read Now →

Python Get File Extension from Filename Example

Read Now →

Python Get First Date of Last Month Example

Read Now →

Python Create Zip Archive from Directory Example

Read Now →

Python List All Dates Between Two Dates Example

Read Now →

How to Check if Today is Saturday or not in Python?

Read Now →

Python PATCH Request with Parameters Example

Read Now →

Python POST Request with Parameters Example

Read Now →