Last modified: Nov 10, 2024 By Alexander Williams
Python csv.writerows(): Write Multiple Rows to CSV Files
The csv.writerows()
method is a powerful feature in Python's CSV module that allows you to write multiple rows of data to a CSV file in a single operation.
Basic Usage of csv.writerows()
Unlike csv.writerow() which writes one row at a time, writerows() accepts an iterable of rows and writes them all at once.
import csv
data = [
['Name', 'Age', 'City'],
['John', '25', 'New York'],
['Alice', '30', 'London'],
['Bob', '35', 'Paris']
]
with open('people.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
Output Format
Name,Age,City
John,25,New York
Alice,30,London
Bob,35,Paris
Working with Dictionary Data
When working with dictionary data, you can combine writerows()
with DictWriter for more structured data writing.
import csv
data = [
{'Name': 'John', 'Age': '25', 'City': 'New York'},
{'Name': 'Alice', 'Age': '30', 'City': 'London'},
{'Name': 'Bob', 'Age': '35', 'City': 'Paris'}
]
fieldnames = ['Name', 'Age', 'City']
with open('people_dict.csv', 'w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
Performance Considerations
writerows() is more efficient than multiple writerow() calls when dealing with large datasets because it reduces the number of file operations.
Error Handling
import csv
try:
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
except IOError:
print("Error writing to CSV file")
Tips and Best Practices
Always use the newline='' parameter when opening files to ensure consistent behavior across different platforms.
Consider using CSV Writer with proper encoding settings when dealing with special characters.
Conclusion
csv.writerows()
is an efficient method for batch writing data to CSV files. It's particularly useful when working with large datasets or when converting from other formats like JSON to CSV.