Create a CSV File Using Python

In this article, I will take you through how to create a CSV file using the Python programming language. CSV means Comma Separated Values, we use it for storing the data that we need to use for further analysis.

If you are learning machine learning or maybe data analysis then you must have seen that most of the tasks we do in Machine Learning start by importing a CSV file. So if you are working with a CSV file then it is also important to know how to create one while doing analysis.

Also, Read – Machine Learning Full Course for free.

CSV File Using Python

To create a CSV file using Python we only need one library that is Pandas. Almost all the tasks related to data handling and data processing are done using pandas in Python.

Let’s see how to create a CSV file using Python pandas. To write something in a CSV file we first need to create a Python dictionary:

import pandas as pd
data_frame = {'room': rooms, 'swimming pool': pools, 'price': prices} 

Now the next thing that we need to do is to create a pandas Data Frame by using our dictionary. We can use the pandas.DataFrame method for this task:

data_frame = pd.DataFrame(data=my_data)

Now as we have created a data frame by using our dictionary we can now easily transfer this data to a CSV file:


Now after executing the code above you can have look at the directory in which working on you will find the CSV file saved as “Data.csv”. 

As you can see I only created the data and simply transferred into a CSV file, this is how these files are created by using a lot more data that we use in tasks like Machine Learning.

I hope you liked this article on how to build a CSV file by using the Python programming language. Feel free to ask your valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1500

Leave a Reply