In this lesson, you will learn how to bridge the gap between Python scripts and spreadsheet software by programmatically reading and writing Comma-Separated Values (CSV) files.
Why CSV?
While JSON is excellent for hierarchical data, CSV remains the industry standard for tabular data exchange. Because it is essentially a plain-text file where rows are separated by newlines and columns by commas, it is universally readable by Excel, Google Sheets, and data analysis tools. Python’s built-in csv module provides a clean interface to handle these files without manually parsing string delimiters, which is prone to errors (like handling commas inside quoted fields).
Reading Data
To read a file, we use csv.reader. This creates an iterator that yields each row as a list of strings:
import csv
with open('data.csv', mode='r', newline='', encoding='utf-8') as file:
reader = csv.reader(file)
header = next(reader) # Skip the header row
for row in reader:
print(f"Processing: {row[0]} - {row[1]}")
Note: Using newline='' is a best practice when opening CSV files to ensure cross-platform consistency in line endings.
Writing Data
Exporting processed results is just as straightforward. By using csv.writer, you can convert lists or tuples into formatted rows.
data_to_save = [["Name", "Score"], ["Alice", 95], ["Bob", 88]]
with open('results.csv', mode='w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerows(data_to_save)
Best Practices
For more complex data, consider csv.DictReader and csv.DictWriter. These allow you to map rows to dictionaries using the header row as keys, making your code significantly more readable when accessing specific columns by name (e.g., row['email']) rather than relying on index numbers.
By leveraging these tools, you ensure that your data integration pipelines are robust, portable, and easily digestible by non-technical stakeholders who rely on spreadsheets to verify your application's output.
Key Takeaway: Use the built-in csv module to handle row-by-row I/O operations, ensuring that your data remains perfectly formatted for spreadsheet compatibility while avoiding the pitfalls of manual string splitting.