Exporting variable to CSV file in Python

Exporting variable to CSV file in Python

To export variables to a CSV file in Python, the csv module from the standard library can be used. However, for more advanced data structures and ease of use, the pandas library is a popular choice.

I'll demonstrate both methods:

1. Using the csv module:

Let's say you have a list of dictionaries, and you want to export this to a CSV file:

import csv # Sample data: List of dictionaries data = [ {"name": "John", "age": 28, "city": "New York"}, {"name": "Marie", "age": 22, "city": "Boston"}, {"name": "Mike", "age": 32, "city": "Chicago"}, ] # Specify the file name filename = "output.csv" # Writing to csv file with open(filename, 'w') as csv_file: writer = csv.DictWriter(csv_file, fieldnames=data[0].keys()) # Write the headers writer.writeheader() # Write the data writer.writerows(data) 

2. Using pandas:

If you're dealing with complex data structures or want more flexibility, pandas is a great choice. First, you need to install it:

pip install pandas 

Then, you can use it to export variables to a CSV file:

import pandas as pd # Sample data: List of dictionaries data = [ {"name": "John", "age": 28, "city": "New York"}, {"name": "Marie", "age": 22, "city": "Boston"}, {"name": "Mike", "age": 32, "city": "Chicago"}, ] # Convert list of dictionaries to DataFrame df = pd.DataFrame(data) # Export DataFrame to CSV df.to_csv("output.csv", index=False) 

Using pandas, you can also handle and export data from various other sources like databases, Excel files, and more. The index=False argument is used to prevent pandas from writing row numbers to the CSV file.


More Tags

jsonpath mpandroidchart facebook-prophet uiwebviewdelegate aem memoization any default-constructor core phpmyadmin

More Programming Guides

Other Guides

More Programming Examples