Last modified: Dec 19, 2024 By Alexander Williams
Export List to CSV in Python
Exporting a list to a CSV file is a common task in Python, whether you’re working with simple or complex data. This article provides examples to help you export lists to CSV files efficiently.
Using the csv Module
The built-in csv
module is a straightforward way to write data to a CSV file.
Exporting a Simple List
import csv
# Define a simple list
data = ["Alice", "Bob", "Charlie"]
# Write to CSV
with open("output.csv", "w", newline="") as file:
writer = csv.writer(file)
for item in data:
writer.writerow([item])
print("CSV file created: output.csv")
This creates a CSV file where each element of the list is written on a new line.
Exporting a List of Lists
For a list of lists, each sublist becomes a row in the CSV file.
# Define a list of lists
data = [
["Name", "Age", "City"],
["Alice", 30, "NY"],
["Bob", 25, "LA"],
["Charlie", 35, "SF"]
]
# Write to CSV
with open("output.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
print("CSV file created: output.csv")
Using writerows()
, you can write multiple rows at once.
Using the pandas Library
The pandas
library offers a more flexible approach for exporting data, especially for structured data.
Exporting a Simple List
import pandas as pd
# Define a simple list
data = ["Alice", "Bob", "Charlie"]
# Create a DataFrame
df = pd.DataFrame(data, columns=["Name"])
# Export to CSV
df.to_csv("output.csv", index=False)
print("CSV file created: output.csv")
The to_csv()
method writes the DataFrame to a CSV file with customizable options.
Exporting a List of Dictionaries
When working with structured data, a list of dictionaries can be exported to CSV easily.
# Define a list of dictionaries
data = [
{"Name": "Alice", "Age": 30, "City": "NY"},
{"Name": "Bob", "Age": 25, "City": "LA"},
{"Name": "Charlie", "Age": 35, "City": "SF"}
]
# Create a DataFrame
df = pd.DataFrame(data)
# Export to CSV
df.to_csv("output.csv", index=False)
print("CSV file created: output.csv")
Each dictionary represents a row, and keys become column headers in the CSV file.
Handling Complex Data
If your list contains complex objects, you can preprocess it into a suitable format, such as a list of dictionaries or lists.
# Define a class
class Person:
def __init__(self, name, age, city):
self.name = name
self.age = age
self.city = city
# Create a list of objects
people = [
Person("Alice", 30, "NY"),
Person("Bob", 25, "LA"),
Person("Charlie", 35, "SF")
]
# Convert objects to dictionaries
data = [{"Name": p.name, "Age": p.age, "City": p.city} for p in people]
# Create a DataFrame
df = pd.DataFrame(data)
# Export to CSV
df.to_csv("output.csv", index=False)
print("CSV file created: output.csv")
Preprocessing complex data ensures compatibility with CSV export methods.
Customizing CSV Output
You can customize the output with options like delimiter, quoting, and line terminator.
# Custom delimiter and quoting
with open("output.csv", "w", newline="") as file:
writer = csv.writer(file, delimiter=";", quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerows(data)
print("CSV file created with custom settings: output.csv")
These options help adapt the output format to specific requirements.
Related Topics
Learn more about CSV operations with articles like reading CSV files or handling CSVs with pandas.
Conclusion
Exporting lists to CSV files in Python is straightforward with tools like csv
and pandas
. Whether working with simple or complex data, these methods provide robust solutions to create well-structured CSV files.
Try these techniques to streamline your data export tasks in Python!