Python

How to Read and Write CSV Files With Python

CSV files are one of the simplest and most widely used formats for storing structured data. From customer records and sales reports to analytics exports and…

D
DevByteTechnical Author
Published
14 min read4 views
How to Read and Write CSV Files With Python

Working with data is an essential part of programming. Whether you're building a data analysis tool, processing customer records, importing product information, or generating reports, you'll often need to work with CSV files.

CSV stands for Comma-Separated Values. It is a widely used file format for storing tabular data in a simple text-based structure. CSV files can be opened using spreadsheet applications, text editors, and many programming languages.

Python makes working with CSV files straightforward. It provides a built-in csv module that allows you to read, write, update, and process CSV data without installing an external library.

In this guide, you'll learn how to read and write CSV files with Python, work with rows and columns, handle dictionaries, append new records, manage errors, and follow best practices through practical examples.

What Is a CSV File?

A CSV file stores tabular data as rows, with individual values separated by a delimiter, commonly a comma.

For example, consider a file named employees.csv:

id,name,department,salary
1,Manjeet,Engineering,45000
2,Rahul,Marketing,38000
3,Priya,Finance,42000

In this example:

  • Each line represents a record.

  • The first row contains column headers.

  • Commas separate individual fields.

  • Each record contains an employee's ID, name, department, and salary.

CSV files are popular because they are lightweight and easy to exchange between applications.

Common Uses of CSV Files

CSV files are frequently used for:

  • Importing and exporting database records.

  • Managing customer and employee information.

  • Exchanging data between different applications.

  • Preparing datasets for data analysis.

  • Exporting reports from web applications.

  • Storing simple tabular information.

  • Loading datasets for machine learning projects.

For example, a Python script can read customer records from a CSV file, calculate statistics, and generate a new report containing the results.

Why Use Python to Work With CSV Files?

Python provides several ways to work with CSV data, but the built-in csv module is a good starting point.

Here are some of its advantages:

1. No additional installation: The csv module comes with Python, so you don't need to install a separate package.

2. Easy file handling: You can read and write CSV files using familiar Python functions.

3. Dictionary support: DictReader and DictWriter let you work with column names instead of numeric indexes.

4. Handles quoted values: The module understands quoted fields containing commas, quotes, and embedded newlines.

5. Flexible formatting: You can configure delimiters, quoting behavior, and other formatting options.

For official details, see the Python CSV documentation.

How to Read a CSV File in Python

Let's start with the simplest example.

Suppose you have a file named employees.csv containing:

id,name,department
1,Manjeet,Engineering
2,Rahul,Marketing
3,Priya,Finance

You can read this file using Python's csv.reader() function.

Step 1: Import the CSV Module

Create a Python file named read_csv.py and add:

import csv

The csv module provides the functions and classes required to process CSV files.

Step 2: Open and Read the File

Add the following code:

import csv

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

    for row in reader:
        print(row)

Output:

['id', 'name', 'department']
['1', 'Manjeet', 'Engineering']
['2', 'Rahul', 'Marketing']
['3', 'Priya', 'Finance']

Let's understand the code.

  • open() opens the CSV file.

  • "r" opens the file in read mode.

  • newline="" allows the CSV module to handle newlines correctly.

  • encoding="utf-8" specifies the text encoding.

  • csv.reader(file) creates an object that reads CSV records.

  • The for loop processes each row.

The with statement automatically closes the file when the block finishes, even if an exception occurs.

Important: By default, csv.reader() returns each field as a string. If you need numeric values for calculations, convert them explicitly.

How to Read Specific Columns From a CSV File

Sometimes, you don't need every column in a dataset. You may want to retrieve only employee names or departments.

You can access individual values using their indexes.

For example:

import csv

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

    next(reader, None)

    for row in reader:
        employee_name = row[1]
        department = row[2]

        print(employee_name, department)

Output:

Manjeet Engineering
Rahul Marketing
Priya Finance

The next(reader, None) statement skips the header row.

Remember that indexes start at zero:

  • row[0] represents the ID.

  • row[1] represents the name.

  • row[2] represents the department.

This approach works, but it can become difficult to maintain when a CSV file contains many columns or its column order changes.

For more readable code, consider using csv.DictReader().

How to Read CSV Files Using DictReader

Python provides csv.DictReader() to read CSV records as dictionaries.

Instead of accessing columns through indexes, you can use their header names.

Consider the following file:

id,name,department
1,Manjeet,Engineering
2,Rahul,Marketing
3,Priya,Finance

Now read it using:

import csv

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

    for row in reader:
        print(row["name"], row["department"])

Output:

Manjeet Engineering
Rahul Marketing
Priya Finance

Each row behaves like a dictionary:

{
    "id": "1",
    "name": "Manjeet",
    "department": "Engineering"
}

Notice that the values are still strings.

Why Is DictReader Useful?

DictReader makes your code easier to understand because you can refer to columns by name.

For example:

if row["department"] == "Engineering":
    print(row["name"])

This is often clearer than comparing a value at a numeric index.

It is particularly useful when processing employee data, product catalogs, customer information, and exported database records.

How to Write a CSV File in Python

Reading existing data is useful, but many applications also need to create CSV files.

Python's csv.writer() lets you write rows into a new file.

Example: Creating a CSV File

Create a file named write_csv.py:

import csv

employees = [
    ["id", "name", "department"],
    [1, "Manjeet", "Engineering"],
    [2, "Rahul", "Marketing"],
    [3, "Priya", "Finance"]
]

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

    writer.writerows(employees)

print("CSV file created successfully!")

Output:

CSV file created successfully!

The generated output.csv file contains:

id,name,department
1,Manjeet,Engineering
2,Rahul,Marketing
3,Priya,Finance

Understanding the Code

  • "w" opens the file in write mode.

  • csv.writer(file) creates a CSV writer.

  • writer.writerows(employees) writes multiple rows.

  • newline="" helps prevent unwanted extra blank lines on platforms where newline handling differs.

Important: Opening an existing file with "w" truncates its previous contents. If you need to preserve existing records, use append mode or write to a separate file.

Difference Between writerow() and writerows()

Python provides two useful methods for writing CSV data.

1. writerow()

The writerow() method writes a single row.

import csv

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

    writer.writerow(["id", "name", "department"])
    writer.writerow([1, "Manjeet", "Engineering"])
    writer.writerow([2, "Rahul", "Marketing"])

This method is useful when generating records individually.

2. writerows()

The writerows() method writes multiple rows from an iterable.

import csv

employees = [
    ["id", "name", "department"],
    [1, "Manjeet", "Engineering"],
    [2, "Rahul", "Marketing"]
]

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

Use writerows() when your data is already available as a collection of records.

How to Write CSV Files Using DictWriter

Just as DictReader makes reading easier, DictWriter lets you write records using dictionaries.

This is helpful when your application stores data in dictionary objects.

For example:

import csv

employees = [
    {
        "id": 1,
        "name": "Manjeet",
        "department": "Engineering"
    },
    {
        "id": 2,
        "name": "Rahul",
        "department": "Marketing"
    },
    {
        "id": 3,
        "name": "Priya",
        "department": "Finance"
    }
]

fieldnames = ["id", "name", "department"]

with open("employees.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.DictWriter(file, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerows(employees)

print("Employee data exported successfully!")

The output file looks like this:

id,name,department
1,Manjeet,Engineering
2,Rahul,Marketing
3,Priya,Finance

What Does writeheader() Do?

The writeheader() method writes the column names specified in fieldnames.

Without it, you would need to write the header row separately.

The fieldnames argument also determines the order of columns in the generated file.

For example:

fieldnames = ["name", "department", "id"]

This produces columns in the order name, department, and id, regardless of the insertion order of keys in each record.

How to Append Data to an Existing CSV File

Sometimes you want to add new records without deleting the existing data.

For this, Python provides append mode, represented by "a".

Suppose employees.csv already contains employee records. You can add another employee like this:

import csv

new_employee = [4, "Amit", "Support"]

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

    writer.writerow(new_employee)

print("New employee added successfully!")

The new record is appended to the end of the file.

Important Considerations

Append mode does not automatically create a header if the file is empty.

If your application must support both creating a new CSV and appending to an existing one, you should check whether the file already contains a header before writing one.

Also, appending records is not the same as updating an existing record. If you need to change an employee's department, you generally need to read the data, modify the relevant record, and rewrite the file, or use a database if the data requires frequent updates.

How to Filter CSV Data Using Python

One of the most common tasks is filtering rows based on a condition.

Suppose employees.csv contains:

id,name,department,salary
1,Manjeet,Engineering,45000
2,Rahul,Marketing,38000
3,Priya,Engineering,52000
4,Amit,Support,35000

You want to retrieve employees from the Engineering department.

You can use csv.DictReader():

import csv

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

    for employee in reader:
        if employee["department"] == "Engineering":
            print(employee["name"])

Output:

Manjeet
Priya

Filter Employees by Salary

Because CSV values are read as strings, convert the salary to a number before comparing it.

import csv

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

    for employee in reader:
        salary = int(employee["salary"])

        if salary > 40000:
            print(employee["name"], salary)

Output:

Manjeet 45000
Priya 52000

This technique is useful for generating reports, filtering customer records, analyzing product data, and preparing datasets for further processing.

For real datasets, validate that salary values are present and numeric before converting them.

How to Handle Commas Inside CSV Values

CSV files sometimes contain values that include commas.

For example, consider a product description:

Laptop, 16GB RAM, 512GB SSD

If you manually split a line using Python's split(","), the description may be incorrectly separated into multiple fields.

The CSV module handles quoted fields correctly.

Example CSV data:

id,product,description
1,Laptop,"16GB RAM, 512GB SSD"
2,Monitor,"27-inch display, 4K resolution"

Read it with:

import csv

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

    for product in reader:
        print(product["product"])
        print(product["description"])

Output:

Laptop
16GB RAM, 512GB SSD
Monitor
27-inch display, 4K resolution

The CSV parser recognizes that commas inside quoted fields belong to the field rather than separating columns.

This is one reason you should generally use the csv module instead of manually splitting CSV lines.

How to Work With Different CSV Delimiters

Not every CSV-style file uses commas to separate values.

Some files use semicolons or tab characters instead.

For example:

id;name;department
1;Manjeet;Engineering
2;Rahul;Marketing

You can specify the delimiter when reading the file:

import csv

with open("employees.csv", "r", newline="", encoding="utf-8") as file:
    reader = csv.reader(file, delimiter=";")

    for row in reader:
        print(row)

Similarly, you can specify a delimiter when writing:

import csv

with open("employees.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.writer(file, delimiter=";")

    writer.writerow(["id", "name", "department"])
    writer.writerow([1, "Manjeet", "Engineering"])

This is useful when working with files exported by applications that use different CSV formatting conventions.

How to Handle Errors When Reading CSV Files

CSV processing can fail for several reasons:

  • The file does not exist.

  • The application lacks permission to read the file.

  • The file uses an unexpected encoding.

  • The CSV data contains malformed records.

  • A field contains a value that cannot be converted into the expected type.

You can handle common file errors with try and except.

import csv

try:
    with open(
        "employees.csv",
        "r",
        newline="",
        encoding="utf-8"
    ) as file:
        reader = csv.DictReader(file)

        for employee in reader:
            print(employee)

except FileNotFoundError:
    print("Error: CSV file not found.")

except PermissionError:
    print("Error: Permission denied.")

except UnicodeDecodeError:
    print("Error: The file encoding is not supported.")

except csv.Error as error:
    print(f"CSV parsing error: {error}")

This example handles common failures, but it is not a complete validation strategy.

For production applications, you should also validate required headers, check field types, handle missing values, and decide what to do when an individual record is invalid.

If you expect inconsistent or malformed CSV files, consider enabling strict parsing where appropriate and reporting the record or line that caused the problem.

How to Read and Write CSV Files With Pandas

Python's built-in csv module is excellent for basic CSV processing.

However, if you're working with data analysis, large tables, or data transformation workflows, the Pandas library can make many tasks more convenient.

Install Pandas:

pip install pandas

Reading a CSV File With Pandas

import pandas as pd

df = pd.read_csv("employees.csv")

print(df)

Pandas loads the CSV data into a DataFrame, which provides operations for filtering, sorting, transforming, and analyzing tabular data.

Filtering Data

import pandas as pd

df = pd.read_csv("employees.csv")

engineering_employees = df[
    df["department"] == "Engineering"
]

print(engineering_employees)

Writing a CSV File With Pandas

import pandas as pd

df = pd.read_csv("employees.csv")

df.to_csv("output.csv", index=False)

print("CSV exported successfully!")

The index=False argument prevents Pandas from adding the DataFrame index as an extra column.

CSV Module vs. Pandas

Feature

Python csv Module

Pandas

Installation

Built into Python

Requires installation

Basic CSV reading and writing

Excellent

Excellent

Dictionary-based records

DictReader and DictWriter

DataFrames and records

Data analysis

Requires more manual code

Rich data-analysis features

Data transformations

Manual or custom logic

Convenient built-in operations

Best suited for

Lightweight file processing

Data analysis and tabular transformations

Which should you choose?

Use the built-in csv module for simple imports, exports, and record-by-record processing. Choose Pandas when you need richer data analysis and transformation features.

Best Practices for Working With CSV Files

Follow these practices to make your Python code safer and easier to maintain.

1. Always Use a Context Manager

Prefer:

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

The context manager closes the file automatically.

2. Use newline=""

When using Python's CSV reader or writer with file objects, open files with newline="" to allow the CSV module to handle newline characters correctly.

3. Specify the Encoding

Using encoding="utf-8" makes the expected encoding explicit. If your source file uses another encoding, configure it accordingly.

4. Use DictReader for Header-Based Data

DictReader makes code more readable when you need to access fields by their column names.

5. Validate Data Before Processing

CSV data may contain empty fields, unexpected values, or invalid numbers.

Validate your input before using it in calculations or storing it in a database.

6. Avoid Loading Huge Files Entirely Into Memory

The built-in CSV reader supports iterating over records one at a time.

This can be useful when processing large files because you don't need to load every row into a list first.

7. Protect Against Spreadsheet Formula Injection

If your application exports user-controlled data that will be opened in spreadsheet software, consider spreadsheet formula injection.

Certain spreadsheet applications may interpret cells beginning with characters such as =, +, -, or @ as formulas.

CSV quoting alone does not reliably prevent formula execution. Assess the intended spreadsheet applications and apply an appropriate, tested sanitization strategy to untrusted exported values.

8. Use a Database for Frequently Updated Data

CSV files are useful for exchanging tabular information, but they are not a substitute for a database when an application needs frequent updates, concurrent access, relationships, transactions, or complex queries.

Frequently Asked Questions

1. How do I read a CSV file in Python?

Import the csv module, open the file, and use csv.reader().

import csv

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

    for row in reader:
        print(row)

2. How do I write data to a CSV file in Python?

Use csv.writer() and its writerow() or writerows() methods.

import csv

with open("output.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.writer(file)
    writer.writerow(["name", "age"])
    writer.writerow(["Manjeet", 25])

3. What is the difference between reader() and DictReader()?

csv.reader() returns each record as a list, while csv.DictReader() returns each record as a dictionary whose keys usually come from the header row.

4. How can I append data to a CSV file?

Open the file in append mode using "a" and write the new record with writerow().

with open("data.csv", "a", newline="", encoding="utf-8") as file:
    writer = csv.writer(file)
    writer.writerow(["Manjeet", 25])

Make sure the file already has the intended header if your CSV format requires one.

5. Do I need to install the CSV module?

No. Python's csv module is part of the standard library.

6. Can Python read CSV files with commas inside values?

Yes. The csv module correctly handles quoted fields containing commas, provided the file follows the expected CSV format.

7. Can I use Pandas instead of the CSV module?

Yes. Pandas provides read_csv() and to_csv() for reading and writing CSV files. It is particularly useful when you need to analyze or transform tabular data.

8. Does Python automatically convert CSV values into numbers?

Generally, no. The standard CSV reader returns fields as strings by default. Convert values explicitly when you need integers, floats, dates, or other data types.

Conclusion

Reading and writing CSV files is a fundamental skill for Python developers who work with data.

Python's built-in csv module provides everything you need for many common tasks, including reading rows, writing records, filtering data, appending information, and handling dictionary-based data.

For straightforward file processing, start with csv.reader() and csv.writer(). When your data has column headers, DictReader and DictWriter can make your code more readable. If you need advanced data analysis, consider using Pandas.

The best way to learn is to practice: create a CSV file, read its records, filter the data, and export the results into a new file.

Once you understand these fundamentals, you'll be better prepared to build Python scripts for data processing, reporting, automation, and backend applications.

For additional examples and formatting options, explore the official Python CSV module documentation.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘