In this lesson, you will learn how to use Python’s built-in csv module to read and write structured, tabular data while ensuring your files remain compatible across different operating systems.
Why use the csv module?
While you could technically write CSV files by manually joining strings with commas, this approach often breaks when your data contains commas, newlines, or quotes. The csv module handles these "edge cases" automatically, ensuring row-based integrity. It also manages line endings, which is crucial because Windows, macOS, and Linux often use different characters to signal the end of a line.
Writing Tabular Data
When working with files, we use the with statement to ensure our resources are properly closed, even if an error occurs. Here is how you can write data into a CSV format:
import csv
data = [
["Name", "Department", "Salary"],
["Alice", "Engineering", 85000],
["Bob", "Design", 72000]
]
with open("employees.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerows(data)
The newline="" argument is vital when opening the file; it prevents Python from performing extra line-ending conversions that could corrupt the CSV structure across different platforms.
Reading Tabular Data
Reading is just as streamlined. The csv module allows us to iterate through the file row by row, keeping memory usage low even if the file is massive:
with open("employees.csv", "r", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader:
print(row)
Each row comes back as a simple Python list. If you prefer to access data by column names (like "Name" or "Salary"), you can use csv.DictReader instead of csv.reader. This maps each row to a dictionary, making your code much more readable when handling complex datasets.
By using these tools, you move away from manual string formatting and rely on a robust, industry-standard way to move data between Python scripts and spreadsheet applications.
Key Takeaway: Always use the csv module with newline="" to ensure your tabular data remains portable and structurally sound across all operating systems.