Skip to content

Q&A · Answered

How to read CSV files in Python

asked 9 months, 1 week ago 1188 views 1 answer
11

What is the best way to read and process CSV files?

1 Answer

One accepted
27

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago
import csv

# Using csv module
with open('data.csv', 'r') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row['column_name'])

# Using pandas (recommended for large files)
import pandas as pd
df = pd.read_csv('data.csv')
print(df.head())

# Write CSV
with open('output.csv', 'w', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=['name', 'age'])
    writer.writeheader()
    writer.writerow({'name': 'John', 'age': 30})

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.