How to Create a CSV File in Python

Pandas to the rescue

Dieter Jordens
Kwal-IT

--

Data
Photo by Mika Baumeister on Unsplash.

In this article, you’ll learn how to construct a CSV file in Python. This can be a great way to save data on which you’ll later do some analysis. A lot of articles start with reading from such a CSV file or DataFrame.

So, you must know how to construct such a file yourself as a data enthusiast. It allows you to play around with, change, and create large CSVs yourself. These files can be found all over the web and playing around with them is a great way to get started with data science.

Installing Pandas

We’ll be using a library named Pandas. Pandas has been around since 2008 and is a flexible, powerful data analysis and manipulation tool. It’s very efficient with small data up to 1GB. If you have a larger file, consider reading it in chunks before moving to a more complex library.

import pandas as pd

Writing to the CSV File

Before we can write something to a CSV file, we have to create a dictionary first. Personally, I like to construct an equal-sized list for each column. That way, we can construct a dictionary in a very readable way:

data_frame = {'room': rooms, 'swimming pool': pools, 'price': prices} 

--

--

Dieter Jordens
Kwal-IT

Owner of https://kwal-it.be - Your expert in the domain of Software Development, Coaching and Content Management