Site icon Full-Stack

How to Read and Write CSV Files in Python

CSV (Comma-Separated Values) files are a common format for storing and exchanging tabular data. Whether you’re working with datasets, reports, or logs—Python makes it easy to read and write CSV files using its built-in csv module or the powerful pandas library.

This beginner-friendly guide will walk you through both methods with clear examples.


Why Use CSV Files?


Method 1: Using Python’s Built-in csv Module

Reading a CSV File

python

Copy code

import csv

with open(“data.csv”, mode=”r”) as file:

    reader = csv.reader(file)

    for row in reader:

        print(row)

Writing to a CSV File

python

Copy code

data = [[“Name”, “Age”], [“Alice”, 30], [“Bob”, 25]]

with open(“output.csv”, mode=”w”, newline=””) as file:

    writer = csv.writer(file)

    writer.writerows(data)

✅ newline=”” prevents extra blank lines in the output on Windows.


Method 2: Using pandas for CSVs

Reading with pandas

python

Copy code

import pandas as pd

df = pd.read_csv(“data.csv”)

print(df.head())

Writing with pandas

python

Copy code

df.to_csv(“new_data.csv”, index=False)

✅ Great for data analysis, filtering, sorting, and cleaning.


Choosing Between csv and pandas

TaskUse csvUse pandas
Small/simple CSV files
Large data analysis
Data filtering/sorting
Custom logic per row

Practice Tip

Try exporting data from a Python list to a CSV file, then read it back and process the rows using both methods. Compare the syntax and performance.


Next Steps in Your Learning

Mastering CSV files is essential for any aspiring data analyst, developer, or automation engineer. It’s your first step into the world of data handling and reporting.

💡 Ready to level up with real projects and mentorship?
👉 https://www.thefullstack.co.in/courses/

You might be like this:-

Python Modules and Packages

What is AWS Lambda?A Beginner’s Guide to Serverless Computing in 2025

Java vs. Kotlin: Which One Should You Learn for Backend Development?

Where to Find Your Salesforce Organization ID

Frequently Asked Questions

What is the best way to read a CSV file in Python?

You can use the built-in csv module or the pandas library to read a CSV file in Python. The pandas library is often preferred because it provides more functionality and is easier to use. For example, you can use the read_csv function from pandas to read a CSV file into a DataFrame.

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

To write data to a CSV file in Python, you can use the writer function from the csv module or the to_csv function from the pandas library. The writer function allows you to write data row by row, while the to_csv function allows you to write a whole DataFrame at once. Both methods are easy to use and provide a lot of flexibility.

What is the difference between the csv module and the pandas library for working with CSV files?

The csv module is a built-in Python module that provides basic functionality for reading and writing CSV files, while the pandas library is a more powerful library that provides data structures and functions for efficiently handling structured data, including CSV files. The pandas library is generally preferred for working with CSV files because it provides more functionality and is easier to use. The pandas library also provides data analysis and manipulation capabilities that are not available in the csv module.

How do I handle missing values when reading a CSV file in Python?

When reading a CSV file in Python, you can handle missing values by using the na_values parameter of the read_csv function from the pandas library. This parameter allows you to specify the values that should be treated as missing or null. You can also use the fillna function to replace missing values with a specific value, such as zero or a mean value.

Can I use Python to read and write CSV files with non-standard delimiters or quote characters?

Yes, you can use Python to read and write CSV files with non-standard delimiters or quote characters. The csv module and the pandas library both provide parameters that allow you to specify the delimiter and quote character. For example, you can use the delimiter parameter of the read_csv function to specify a delimiter other than the comma, such as a semicolon or a tab.

Exit mobile version