You can save data to a CSV file in Python using the built-in csv module or libraries like pandas. Below are examples for both methods:
Method 1: Using the csv Module
The csv module is part of Python’s standard library and provides functions for writing to CSV files.
pythonCopy code
import csv
# Sample data
data = [
[‘Name’, ‘Age’, ‘City’],
[‘Alice’, 30, ‘New York’],
[‘Bob’, 25, ‘Los Angeles’],
[‘Charlie’, 35, ‘Chicago’]]
# Write data to a CSV file
with open(‘output.csv’, ‘w’, newline=”) as file:
writer = csv.writer(file)
writer.writerows(data)
print(“Data has been saved to ‘output.csv’.”)
Method 2: Using pandas
The pandas library is powerful for handling and exporting data, especially in tabular format.
Python Copy code
import pandas as pd
# Sample data
data = {
‘Name’: [‘Alice’, ‘Bob’, ‘Charlie’],
‘Age’: [30, 25, 35],
‘City’: [‘New York’, ‘Los Angeles’, ‘Chicago’]}
# Create a DataFrame
df = pd.DataFrame(data)
# Write the DataFrame to a CSV file
df.to_csv(‘output.csv’, index=False)
print(“Data has been saved to ‘output.csv’.”)
Key Differences:
The csv module is lightweight and suitable for simple tasks.
pandas is more feature-rich and better for working with large or complex datasets.
Both methods will create a file named output.csv in the current working directory.