Wednesday, January 15, 2025
HomeProgrammingHow can I save data to a CSV file using Python?

How can I save data to a CSV file using Python?

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 = [

See also  How do I use valgrind to find memory leaks?

[‘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

See also  How to wrap text in CSS

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.

See also  Java Future Example

Both methods will create a file named output.csv in the current working directory.

 

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x