Python CSV: Reading and Writing Spreadsheets
Learn how to handle CSV data in Python. Master csv.reader, csv.writer, and DictReader/DictWriter for efficient table parsing.
Overview
CSV (Comma-Separated Values) is a ubiquitous format for exporting and importing data from spreadsheets and relational databases. Because CSV files are simple text files, they are universally supported by analytical tools, database platforms, and programming languages. Python features a built-in `csv` module specifically optimized for parsing, writing, and manipulating tabular data without needing third-party libraries like pandas.
The csv module provides two primary interfaces: list-based readers/writers and dictionary-based readers/writers. `csv.reader()` and `csv.writer()` represent each line in the CSV as a list of strings, which is simple but requires referencing columns by their numerical index. For a more robust approach, developers use `csv.DictReader()` and `csv.DictWriter()`. These classes map each row to a dictionary using the CSV header row as keys, producing highly readable code that doesn't break if columns are reordered.
When dealing with CSV files, syntax details matter. Different programs use different delimiters (like tabs or semicolons) and handle quotes or line endings in distinct ways. The `csv` module allows you to define custom delimiters, quoting rules, and escape characters via a 'dialect' parameter. Additionally, when opening CSV files in Python, it is a critical requirement to pass `newline=''` to the `open()` function to prevent blank line issues across different operating systems.
Code Example
Writing data to a CSV file using DictWriter and reading it back with DictReader.
import csv
filename = "employees.csv"
fieldnames = ["id", "name", "department"]
data = [
{"id": "101", "name": "Bob", "department": "HR"},
{"id": "102", "name": "Alice", "department": "Engineering"}
]
# Write dict data to CSV
with open(filename, "w", newline="") as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
print("CSV written successfully.\n--- Reading CSV ---")
# Read CSV data back as dictionaries
with open(filename, "r", newline="") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(f"Employee {row['name']} works in {row['department']}.")CSV written successfully.
--- Reading CSV ---
Employee Bob works in HR.
Employee Alice works in Engineering.Real-world Use Cases
- Exporting spreadsheet records for financial analysis
- Importing contact list catalogs into databases
- Formatting statistical outputs from computational scripts
Frequently Asked Questions
Why do I need to specify newline="" when opening a CSV file?
This is required by the csv module's internal writer to prevent extra blank lines from being inserted, particularly on Windows platforms.
How can I parse a CSV file that uses tabs instead of commas?
You can pass the delimiter parameter to the reader or writer, e.g., csv.reader(file, delimiter='\t').
Keep Learning
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
How to Read and Parse a CSV File in Python
Learn how to read and parse CSV files in Python using the built-in csv module. Master reading as lists, dictionary readers, and custom delimiters.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.