Python24 min read
Python Working with CSV
Read and write CSV files correctly using csv module and pandas, handle headers, delimiters, and large datasets for data analysis and automation.
David Miller
August 31, 2025
3.8k181
CSV is one of the most common file formats for data sharing.
You will use CSV when:
- exporting reports
- moving data between systems
- working with spreadsheets
- doing analytics
## Reading CSV using csv.reader
```python
import csv
with open("data.csv", "r", newline="") as file:
reader = csv.reader(file)
header = next(reader) # skip header
for row in reader:
print(row)
```
## Writing CSV using csv.writer
```python
import csv
rows = [
["Name", "Age", "City"],
["Tom", 25, "Austin"],
["Sarah", 28, "Miami"]
]
with open("output.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(rows)
```
## DictReader and DictWriter (best for real apps)
```python
import csv
with open("data.csv", "r", newline="") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["Name"], row["Age"])
```
```python
import csv
data = [
{"Name": "Tom", "Age": 25, "City": "Austin"},
{"Name": "Sarah", "Age": 28, "City": "Miami"}
]
with open("output.csv", "w", newline="") as file:
writer = csv.DictWriter(file, fieldnames=["Name", "Age", "City"])
writer.writeheader()
writer.writerows(data)
```
## Custom delimiter (TSV or pipe-separated)
```python
import csv
with open("data.tsv", "r", newline="") as file:
reader = csv.reader(file, delimiter="\t")
for row in reader:
print(row)
```
## Pandas (best for analysis + big data)
```python
import pandas as pd
df = pd.read_csv("data.csv")
print(df.head())
df.to_csv("cleaned.csv", index=False)
```
## Graph: CSV workflow
```mermaid
flowchart LR
A[CSV file] --> B[Read: csv/pandas]
B --> C[Clean/transform]
C --> D[Write new CSV]
D --> E[Share/report/import]
```
## Remember
- Use newline="" when writing CSV (important)
- DictReader is easier in apps
- Pandas is best for large datasets and analysis
#Python#Advanced#CSV