How to read CSV file in Python?

Using the csv Module

The csv module provides functionality for reading and writing CSV files. Here’s an example:

import csv

# Open the CSV file
with open('example.csv', mode='r') as file:
    reader = csv.reader(file)
    
    # Iterate through each row
    for row in reader:
        print(row)  # Each row is a list of values

If the CSV file has a header and you want to access rows as dictionaries:

import csv

# Open the CSV file
with open('example.csv', mode='r') as file:
    reader = csv.DictReader(file)
    
    # Iterate through each row
    for row in reader:
        print(row)  # Each row is an OrderedDict

Using pandas Library

pandas is a powerful library for data analysis and manipulation. It’s widely used for handling tabular data like CSVs.

import pandas as pd

# Read the CSV file into a DataFrame
df = pd.read_csv('example.csv')

# Display the DataFrame
print(df)

# Access specific columns or rows
print(df['ColumnName'])  # Access a column
print(df.iloc[0])       # Access a specific row

Key Points

  • csv Module: lightweight, standard module in Python’s standard library, though somewhat weaker when it comes to data manipulation.
  • pandas: Needs to be installed (pip install pandas). But it is a good library for data manipulation and analysis.