Home Course Roadmap
PyLearn Python Course Python CSV
Lesson 38 Files & Data

Python CSV

Learn how to read, write, update and process CSV files using Python's built-in csv module.

45–55 minutes Beginner Files & Data
0%
01

Learning Objectives

What you will learn in this lesson

  • Understand what CSV files are.
  • Understand how rows and columns are represented.
  • Use Python's built-in csv module.
  • Read CSV files using csv.reader().
  • Work with CSV headers.
  • Read structured rows using DictReader.
  • Create CSV files using csv.writer().
  • Write dictionary-based data using DictWriter.
  • Append new records to CSV files.
  • Process and analyze CSV data using Python.
02

What Is CSV?

Understanding comma-separated values

CSV stands for Comma-Separated Values.

A CSV file is a simple text file used to store tabular data in rows and columns.

For example, a student dataset might look like this:

students.csv
name,age,marks
Ali,20,85
Sara,22,92
Ahmed,21,78

Each line represents a row, while commas separate individual values.

Simple Idea

A CSV file is essentially a simple way of storing table-like information in plain text.

03

Why CSV Is Important

Where CSV files are used

CSV files are extremely common in business, data analysis and software development.

Common Uses

  • Excel exports
  • Customer records
  • Sales reports
  • Employee data
  • Product inventories
  • Student records
  • Marketing data
  • Data analysis projects
  • Importing and exporting datasets

CSV is particularly useful because almost every spreadsheet application can open CSV files.

Microsoft Excel, Google Sheets and many data-analysis tools can work with CSV files.

04

CSV Structure

Rows, columns and headers

Consider this CSV file:

employees.csv
name,department,salary
Ali,Sales,60000
Sara,Marketing,75000
Ahmed,IT,90000

The first row is commonly used as the header row.

Table Representation
name     | department | salary
---------|------------|-------
Ali      | Sales      | 60000
Sara     | Marketing  | 75000
Ahmed    | IT         | 90000

The header tells us what each column represents.

05

The csv Module

Python's built-in CSV tools

Python includes a built-in module named csv.

Importing csv
import csv

No external installation is required. The module is included with Python.

Important CSV Tools

  • csv.reader()
  • csv.DictReader()
  • csv.writer()
  • csv.DictWriter()
06

Reading a CSV File

Opening and processing CSV data

The first step is to open the CSV file using Python's open() function.

Opening a CSV file
import csv

with open("students.csv", "r", encoding="utf-8") as file:
    reader = csv.reader(file)

    for row in reader:
        print(row)

Each row returned by csv.reader() is represented as a list.

Output
['name', 'age', 'marks']
['Ali', '20', '85']
['Sara', '22', '92']
['Ahmed', '21', '78']

Important

Values read from a CSV file are normally strings. If you need numbers, you may need to convert them.

07

csv.reader()

Reading rows as lists

csv.reader() is useful when you want direct access to each row and column by position.

Accessing columns
import csv

with open("students.csv", "r", encoding="utf-8") as file:

    reader = csv.reader(file)

    next(reader)

    for row in reader:
        name = row[0]
        age = int(row[1])
        marks = int(row[2])

        print(name, marks)
Output
Ali 85
Sara 92
Ahmed 78

next(reader) skips the header row.

08

Working with Headers

Understanding the first row

Many CSV files contain a header row. You can capture the header separately.

Reading headers
import csv

with open("students.csv", "r", encoding="utf-8") as file:

    reader = csv.reader(file)

    headers = next(reader)

    print("Headers:", headers)

    for row in reader:
        print(row)
Output
Headers: ['name', 'age', 'marks']
['Ali', '20', '85']
['Sara', '22', '92']
['Ahmed', '21', '78']
09

csv.DictReader()

Reading rows as dictionaries

DictReader makes CSV data easier to work with because each row becomes a dictionary.

DictReader example
import csv

with open("students.csv", "r", encoding="utf-8") as file:

    reader = csv.DictReader(file)

    for student in reader:
        print(student["name"])
        print(student["marks"])
Output
Ali
85
Sara
92
Ahmed
78

Why DictReader Is Useful

Instead of remembering that marks are in column 2, you can simply use student["marks"].

10

Writing CSV Files

Creating structured CSV data

Python can also create CSV files.

The basic workflow is:

  1. Open a file in write mode.
  2. Create a CSV writer.
  3. Write the header.
  4. Write the rows.
  5. Close the file using with.
Creating a CSV file
import csv

with open("students.csv", "w", newline="", encoding="utf-8") as file:

    writer = csv.writer(file)

    writer.writerow(["name", "age", "marks"])

    writer.writerow(["Ali", 20, 85])
    writer.writerow(["Sara", 22, 92])
    writer.writerow(["Ahmed", 21, 78])
11

csv.writer()

Writing rows and columns

csv.writer() provides methods for writing rows into a CSV file.

writerow()

Writing one row
writer.writerow(["Ali", 20, 85])

writerows()

Use writerows() to write multiple rows.

Writing multiple rows
rows = [
    ["Ali", 20, 85],
    ["Sara", 22, 92],
    ["Ahmed", 21, 78]
]

writer.writerows(rows)
12

csv.DictWriter()

Writing dictionary-based records

DictWriter allows you to write dictionaries directly into a CSV file.

DictWriter example
import csv

fieldnames = ["name", "age", "marks"]

students = [
    {"name": "Ali", "age": 20, "marks": 85},
    {"name": "Sara", "age": 22, "marks": 92},
    {"name": "Ahmed", "age": 21, "marks": 78}
]

with open("students.csv", "w", newline="", encoding="utf-8") as file:

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

    writer.writeheader()
    writer.writerows(students)

Professional Approach

DictWriter is often convenient when your application already stores records as dictionaries.

13

Appending CSV Data

Adding new records without replacing existing ones

Use mode "a" when you want to append new rows to an existing CSV file.

Appending a student
import csv

with open("students.csv", "a", newline="", encoding="utf-8") as file:

    writer = csv.writer(file)

    writer.writerow(["Usman", 23, 88])

Be Careful

When using append mode, do not repeatedly write the header unless you intentionally want another header row.

14

Delimiters

CSV does not always use commas

Although CSV commonly means comma-separated values, files can use other delimiters such as semicolons or tabs.

For example:

Semicolon-separated data
name;age;marks
Ali;20;85
Sara;22;92

You can specify the delimiter when reading the file.

Custom delimiter
import csv

with open("students.csv", "r", encoding="utf-8") as file:

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

    for row in reader:
        print(row)
15

Quoting & Special Values

Handling commas and complex text

CSV files may contain text that itself includes commas. Quoting allows the CSV format to distinguish between commas inside a value and commas separating columns.

Example
name,address
Ali,"House 10, Street 5, Multan"
Sara,"House 20, Street 8, Lahore"

Python's csv module handles CSV quoting rules for you.

Writing text containing commas
import csv

with open("customers.csv", "w", newline="", encoding="utf-8") as file:

    writer = csv.writer(file)

    writer.writerow(["name", "address"])

    writer.writerow([
        "Ali",
        "House 10, Street 5, Multan"
    ])
16

The newline Parameter

A small detail that matters

When writing CSV files in Python, it is recommended to use:

Recommended file opening
with open(
    "students.csv",
    "w",
    newline="",
    encoding="utf-8"
) as file:

    writer = csv.writer(file)

The newline="" setting allows the CSV module to handle line endings correctly.

Good Habit

Whenever you write CSV files with Python, remember the combination: newline="" and encoding="utf-8".

17

CSV Encoding

Working with international text

CSV files may contain names, addresses and other information in many languages.

Using UTF-8 encoding helps Python handle a wide range of characters.

UTF-8 CSV
with open(
    "customers.csv",
    "r",
    encoding="utf-8"
) as file:

    reader = csv.reader(file)

    for row in reader:
        print(row)

Best Practice

Explicitly specifying encoding="utf-8" makes your programs more predictable when working with international data.

18

Processing CSV Data

Turning raw CSV rows into useful information

CSV becomes much more powerful when combined with Python's calculations, conditions and loops.

Example — Calculate Average Marks

CSV analysis
import csv

total = 0
count = 0

with open("students.csv", "r", encoding="utf-8") as file:

    reader = csv.DictReader(file)

    for student in reader:

        marks = int(student["marks"])

        total += marks
        count += 1

average = total / count

print("Average:", average)
Output
Average: 85.0

Example — Find High Scorers

Filtering records
import csv

with open("students.csv", "r", encoding="utf-8") as file:

    reader = csv.DictReader(file)

    for student in reader:

        marks = int(student["marks"])

        if marks >= 90:
            print(student["name"])
Output
Sara
19

Real-World Examples

How CSV is used in practical applications

1. Sales Reports

A business might export its sales information into a CSV file:

sales.csv
product,quantity,price
Laptop,5,85000
Mouse,20,2500
Keyboard,12,4500

2. Customer Records

customers.csv
name,email,city
Ali,ali@example.com,Multan
Sara,sara@example.com,Lahore
Ahmed,ahmed@example.com,Islamabad

3. Data Analysis

Analysts frequently receive datasets as CSV files. Python can read these files and calculate totals, averages, filter records and generate reports.

Your Future Lessons

Later in PyLearn, you will learn NumPy, Pandas and data analysis techniques that make large CSV datasets much easier to process.

20

Common CSV Mistakes

Problems beginners often encounter

1. Forgetting to import csv

import csv

2. Using the wrong file mode

Use "r" for reading, "w" for replacing/writing, and "a" for appending.

3. Forgetting newline=""

When writing CSV files, use:

open("data.csv", "w", newline="", encoding="utf-8")

4. Forgetting that CSV values are strings

age = int(row["age"])
salary = float(row["salary"])

5. Accidentally writing the header repeatedly

Be careful when using append mode. Headers normally belong only at the top of the file.

6. Assuming every CSV uses commas

Some files use semicolons, tabs or other delimiters.

21

Practice Exercises

Strengthen your CSV skills

Exercise 1 — Read a CSV

Create a CSV file containing five students and print every row using csv.reader().

Exercise 2 — Skip the Header

Read a CSV file and use next() to skip its header.

Exercise 3 — Use DictReader

Read a student CSV file using csv.DictReader() and print each student's name.

Exercise 4 — Create a CSV

Create an employee CSV containing name, department and salary.

Exercise 5 — Append Data

Add a new employee to the existing CSV without deleting previous records.

Exercise 6 — Calculate Total

Read a sales CSV and calculate total revenue.

Exercise 7 — Find High Salaries

Read an employee CSV and display employees whose salary is greater than 100,000.

Exercise 8 — DictWriter

Create a CSV file using csv.DictWriter().

22

Mini Challenge — Sales Report Analyzer

Build a practical CSV-based application

Build a small Python program that reads sales information from a CSV file and generates a report.

Your Program Should

  1. Create a sales.csv file.
  2. Store product, quantity and price.
  3. Read the file using DictReader.
  4. Calculate revenue for each product.
  5. Calculate total revenue.
  6. Find the product with the highest revenue.
  7. Count the total number of products sold.
  8. Display a professional summary.

Suggested CSV

sales.csv
product,quantity,price
Laptop,5,85000
Mouse,20,2500
Keyboard,12,4500
Monitor,4,35000

Expected Report

Example
===== SALES REPORT =====

Total Units Sold: 41
Total Revenue: 618000

Top Product:
Laptop

=========================

Challenge Goal

This challenge combines CSV reading, dictionary access, loops, type conversion, calculations and conditional logic.

23

Quick Knowledge Check

Test what you learned

1. What does CSV stand for?

2. Which Python module is used for CSV files?

3. What does csv.reader() return for each row?

4. Which class reads CSV rows as dictionaries?

5. Which function writes one row to a CSV file?

6. Which mode is normally used to append data?

7. What does DictWriter work with?

8. Why is newline="" commonly used when writing CSV files?

9. What type are CSV values usually read as?

10. Which parameter can specify a semicolon instead of a comma?

24

Lesson Summary

What you should remember

Key Takeaways

  • CSV stands for Comma-Separated Values.
  • CSV files store tabular information in rows and columns.
  • Python provides the built-in csv module.
  • csv.reader() reads rows as lists.
  • csv.DictReader() reads rows as dictionaries.
  • csv.writer() writes rows to CSV files.
  • csv.DictWriter() writes dictionary-based records.
  • Use "a" mode to append new records.
  • CSV values are normally read as strings and may need conversion.
  • The delimiter can be changed when a CSV uses something other than commas.
  • newline="" is recommended when writing CSV files.
  • CSV is widely used for business reports, customer data and data analysis.

You now have the skills to create, read and process practical CSV datasets using Python.

Excellent work!

You've completed Python CSV. Mark this lesson complete and continue your journey.