How to read CSV files in Python
Answered
11
What is the best way to read and process CSV files?
H
Asked by
hassan_ops
Bronze
•
565 rep
1 Answer
27
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})
Y
Platinum
•
311 rep
Your Answer
You need to be logged in to answer questions.
Log In to Answer