Saving data to a CSV file using Python

problem

You have a program in Python and wish to save some data to a CSV file. This can easily be done using the pandas library.

SOLUTION

Using pandas library and DataFrame. By using DataFrame object, data are stored in a Spreadsheet style with columns and rows. Following that, they can easily be exported to a CSV. An example is shown below:

save_csv.py
				
					import pandas as pd


def save_csv():
    some_data = {
        'Color': ['blue', 'red', 'yellow', 'green'],
        'Like': [2, 3, 1, 9]
    }

    dataframe = pd.DataFrame(some_data)
    dataframe.to_csv('some_data.csv')


if __name__ == '__main__':
    save_csv()
				
			

Easy. Create the DataFrame from the data you wish to save and then call the to_csv() function giving a filename.

running

If running it in a terminal:

				
					python3 save_csv.py
				
			
output

It will create a local file some_data.csv

Opening the created CSV file in a spreadsheet application (e.g Excel or Numbers in this case):

Interestingly, the DataFrame can export data to HTML too. For example using the to_html() function:

				
					dataframe.to_html('some_data.html')
				
			

This will generate the HTML code for the <table> as shown below (opened in Firefox)

conclusion

In this post we saw how easy it is to export some data from memory to a CSV file using pandas library. The DataFrame also supports exporting to sql, excel, clipboard, json, and others. You can check out their documentation for more details.

 

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

Google Analytics Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.

HotJar Cookies

We use Hotjar in order to better understand our users’ needs and to optimize this service and experience. Hotjar is a technology service that helps us better understand our users’ experience (e.g. how much time they spend on which pages, which links they choose to click, what users do and don’t like, etc.) and this enables us to build and maintain our service with user feedback. Hotjar uses cookies and other technologies to collect data on our users’ behavior and their devices. This includes a device's IP address (processed during your session and stored in a de-identified form), device screen size, device type (unique device identifiers), browser information, geographic location (country only), and the preferred language used to display our website. Hotjar stores this information on our behalf in a pseudonymized user profile. Hotjar is contractually forbidden to sell any of the data collected on our behalf.

For further details, please see the ‘about Hotjar’ section of Hotjar’s support site.