How to read a CSV file in Python?

Published on Aug. 22, 2023, 12:17 p.m.

To read a CSV file in Python, you can use the csv library or the pandas library. Here are two examples using both methods:

  1. Using the csv library:

import csv

with open(‘file.csv’, ‘r’) as file:
reader = csv.reader(file)
for row in reader:
print(row)


2. Using the `pandas` library:

import pandas as pd

df = pd.read_csv(‘file.csv’)
print(df)



Both methods involve opening the CSV file and reading its contents, but the `csv` library is more low-level and provides fine-grained control over reading and writing CSV files. Meanwhile, the `pandas` library provides a high-level interface to read, manipulate, and analyze CSV data using a `DataFrame` object.

Tags: