DEV Community

Jarod Chen
Jarod Chen

Posted on

How to read CSV file in Python?

It's a simple way to read CSV file in Python.

1. Read csv

filename: example.csv

import csv
with open('example.csv', newline='') as csvfile:
  rows = csv.reader(csvfile)
  for row in rows:
    print(row)

2. Read csv in Dictionary

If there are data of following format:
Date ,Open, Close
2020/01/01, 100, 200
2020/01/02, 120, 200
You can fetch specific column by csv.DictReader.

import csv
with open('example.csv', newline='') as csvfile:
  rows = csv.DictReader(csvfile)
  for row in rows:
    print(row['Date'], row['Close'])

Top comments (0)