Handling CSV Files

How to work with CSV file in Python.

CSV (Comma-Separated Values) files are widely used to store tabular data, such as spreadsheets and databases. Python provides multiple ways to work with CSV files, including the built-in csv module and pandas. Lets understand csv module first and we will learn handling csv files using pandas in seperate section.

Python’s built-in csv module provides functionality to read from and write to CSV files.

Before working with CSV, import the csv module:

import csv

Reading a CSV File

Use csv.reader() to read a CSV file.

with open("data.csv", "r") as file:
    reader = csv.reader(file)  # Create a CSV reader object
    for row in reader:
        print(row)  # Each row is a list

Skipping the Header Row You can skip the header row at the top.

with open("data.csv", "r") as file:
    reader = csv.reader(file)
    next(reader)  # Skip the header row
    for row in reader:
        print(row)

Reading as a Dictionary Use csv.DictReader() to read CSV rows as dictionaries.

with open("data.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row["Name"], row["Age"])  # Access values using column names

Writing to a CSV File

Use csv.writer() to write data to a CSV file.

with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age", "City"])  # Writing header
    writer.writerow(["Jasmeet", 25, "New York"])
    writer.writerow(["Chris", 30, "Los Angeles"])

Writing Multiple Rows

data = [
    ["Name", "Age", "City"],
    ["Jasmeet", 25, "New York"],
    ["Chris", 30, "Los Angeles"],
]

with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(data)  # Writing multiple rows

Writing from a Dictionary Use csv.DictWriter() to write dictionaries to a CSV file.

data = [
    {"Name": "Jasmeet", "Age": 25, "City": "New York"},
    {"Name": "Chris", "Age": 30, "City": "Los Angeles"},
]

with open("data.csv", "w", newline="") as file:
    fieldnames = ["Name", "Age", "City"]
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()  # Write column names
    writer.writerows(data)

Key points

  • Use csv module for simple file operations.
  • Use pandas for advanced data manipulation and analysis.
  • Handle exceptions to avoid errors while reading/writing files.
No questions available.