11
What is the best way to read and process CSV files?
Loading...
Q&A · Answered
What is the best way to read and process CSV files?
Accepted answer
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})Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.