Lesson 46 of 70 – Python CSV Files
66%

Python CSV Files

CSV stands for Comma-Separated Values. A CSV file is a simple text file used to store tabular data such as student records, employee information, product details, and marks.

Note: Python provides the built-in csv module to read and write CSV files.

What is a CSV File?

A CSV file stores data in rows and columns. Each row represents a record and values in a row are normally separated by commas.

Example:

Name,Age,City
Rahul,20,Patna
Amit,22,Delhi
Priya,21,Jaipur

Here, the first row contains column headings and the following rows contain data.

CSV File Extension

CSV files normally use the .csv extension.

students.csv

CSV files can be opened using applications such as Microsoft Excel, Google Sheets, or a text editor.

Importing the CSV Module

Python provides the csv module as part of its standard library. We can import it using the import statement.

import csv

After importing the module, we can use its functions and classes for working with CSV files.

Reading a CSV File

The csv.reader() function is used to read rows from a CSV file.

import csv

with open("students.csv", "r") as file:

    reader = csv.reader(file)

    for row in reader:
        print(row)

Each row is returned as a list.

Example CSV Data

Suppose students.csv contains:

Name,Age,City
Rahul,20,Patna
Amit,22,Delhi
Priya,21,Jaipur

Python code:

import csv

with open("students.csv", "r") as file:

    reader = csv.reader(file)

    for row in reader:
        print(row)

Output:

['Name', 'Age', 'City']
['Rahul', '20', 'Patna']
['Amit', '22', 'Delhi']
['Priya', '21', 'Jaipur']

Skipping the Header Row

Sometimes we want to process only the data and skip the column headings.

import csv

with open("students.csv", "r") as file:

    reader = csv.reader(file)

    next(reader)

    for row in reader:
        print(row)

The next() function moves the reader to the next row. In this example, it skips the first row.

Accessing CSV Columns

Each row returned by csv.reader() is a list, so we can access individual values using indexes.

import csv

with open("students.csv", "r") as file:

    reader = csv.reader(file)

    next(reader)

    for row in reader:
        print("Name:", row[0])
        print("Age:", row[1])
        print("City:", row[2])

Using csv.DictReader()

The DictReader class reads each CSV row as a dictionary. The column headings are used as dictionary keys.

import csv

with open("students.csv", "r") as file:

    reader = csv.DictReader(file)

    for row in reader:
        print(row["Name"])
        print(row["City"])

This can make the code easier to understand because we can use column names instead of numeric indexes.

Writing to a CSV File

The csv.writer() function is used to write data to a CSV file.

import csv

with open("students.csv", "w", newline="") as file:

    writer = csv.writer(file)

    writer.writerow(["Name", "Age", "City"])

    writer.writerow(["Rahul", 20, "Patna"])
    writer.writerow(["Amit", 22, "Delhi"])
    writer.writerow(["Priya", 21, "Jaipur"])

Why Use newline=""?

When writing CSV files, using newline="" helps prevent unwanted blank lines on some platforms.

with open("students.csv", "w", newline="") as file:
    writer = csv.writer(file)

It is a common practice when using Python's CSV writer.

writerow()

The writerow() method writes one row to a CSV file.

import csv

with open("data.csv", "w", newline="") as file:

    writer = csv.writer(file)

    writer.writerow(["Name", "Age"])
    writer.writerow(["Rahul", 20])

writerows()

The writerows() method writes multiple rows at once.

import csv

data = [
    ["Rahul", 20],
    ["Amit", 22],
    ["Priya", 21]
]

with open("students.csv", "w", newline="") as file:

    writer = csv.writer(file)

    writer.writerow(["Name", "Age"])

    writer.writerows(data)

Using csv.DictWriter()

The DictWriter class is used to write dictionaries to a CSV file.

import csv

with open("students.csv", "w", newline="") as file:

    fields = ["Name", "Age", "City"]

    writer = csv.DictWriter(file, fieldnames=fields)

    writer.writeheader()

    writer.writerow({
        "Name": "Rahul",
        "Age": 20,
        "City": "Patna"
    })

    writer.writerow({
        "Name": "Amit",
        "Age": 22,
        "City": "Delhi"
    })

writeheader()

The writeheader() method writes the field names as the first row of a CSV file.

fields = ["Name", "Age", "City"]

writer = csv.DictWriter(
    file,
    fieldnames=fields
)

writer.writeheader()

CSV Delimiter

A delimiter is the character used to separate values. The default delimiter for csv.reader() and csv.writer() is a comma.

We can use another delimiter, such as a semicolon.

import csv

with open("data.csv", "r") as file:

    reader = csv.reader(file, delimiter=";")

    for row in reader:
        print(row)

Appending Data to CSV

Use the a mode when you want to add new rows without deleting existing data.

import csv

with open("students.csv", "a", newline="") as file:

    writer = csv.writer(file)

    writer.writerow(["Neha", 23, "Mumbai"])

The new row is added at the end of the file.

Creating CSV from a List

We can create a CSV file directly from a list of lists.

import csv

students = [
    ["Name", "Age", "Course"],
    ["Rahul", 20, "Python"],
    ["Amit", 22, "Java"],
    ["Priya", 21, "SQL"]
]

with open("students.csv", "w", newline="") as file:

    writer = csv.writer(file)

    writer.writerows(students)

Creating CSV from Dictionaries

import csv

students = [
    {
        "name": "Rahul",
        "age": 20,
        "course": "Python"
    },
    {
        "name": "Amit",
        "age": 22,
        "course": "Java"
    }
]

with open("students.csv", "w", newline="") as file:

    fields = ["name", "age", "course"]

    writer = csv.DictWriter(
        file,
        fieldnames=fields
    )

    writer.writeheader()

    writer.writerows(students)

CSV Quoting

CSV data may contain commas or other special characters inside values. The CSV module provides quoting options to handle such data correctly.

import csv

with open("data.csv", "w", newline="") as file:

    writer = csv.writer(
        file,
        quoting=csv.QUOTE_ALL
    )

    writer.writerow(["Rahul", "Patna"])

The QUOTE_ALL option places quotes around all fields.

Practical Example – Student Records

The following program reads student records from a CSV file and displays each student's information.

import csv

with open("students.csv", "r") as file:

    reader = csv.DictReader(file)

    for student in reader:

        print("Name:", student["Name"])
        print("Age:", student["Age"])
        print("City:", student["City"])
        print("----------------")

Complete CSV Example

import csv

students = [
    ["Rahul", 20, "Patna"],
    ["Amit", 22, "Delhi"],
    ["Priya", 21, "Jaipur"]
]

# Write data
with open("students.csv", "w", newline="") as file:

    writer = csv.writer(file)

    writer.writerow(["Name", "Age", "City"])

    writer.writerows(students)


# Read data
with open("students.csv", "r") as file:

    reader = csv.reader(file)

    for row in reader:
        print(row)

This example first creates a CSV file and then reads the data from it.

Important CSV Tools

Tool Purpose
csv.reader() Reads CSV rows
csv.writer() Writes CSV rows
csv.DictReader() Reads CSV rows as dictionaries
csv.DictWriter() Writes dictionaries to CSV
writerow() Writes one row
writerows() Writes multiple rows
writeheader() Writes dictionary field names as a header

Advantages of CSV Files

  • Simple and easy to understand
  • Easy to create and edit
  • Can be opened in spreadsheet applications
  • Useful for storing tabular data
  • Easy to process using Python
  • Suitable for importing and exporting data

Key Points

  • CSV means Comma-Separated Values.
  • Python provides the built-in csv module.
  • Use csv.reader() to read CSV data.
  • Use csv.writer() to write CSV data.
  • Use DictReader to read rows as dictionaries.
  • Use DictWriter to write dictionaries.
  • writerow() writes one row.
  • writerows() writes multiple rows.
  • Use a mode to append data.
  • Use newline="" when writing CSV files.

🧠 Quick Quiz

Question: Which Python function is commonly used to read rows from a CSV file?