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