Lesson 11 – How to Read and Write CSV Files in Python: A Beginner’s Guide
Working with CSV files is an essential skill for any Python programmer, especially if you’re starting to explore data analysis or automation. CSV (Comma-Separated Values) files are one of the most common ways to store structured data, and Python makes it super easy to read and write these files.
PYTHON
Leonardo Gomes Guidolin
4/15/20252 min read
🔹 Introduction
In this tutorial, you'll learn step-by-step how to:
Understand what a CSV file is
Read data from a CSV file using both csv and pandas
Write data to a CSV file
Avoid common mistakes beginners make
Let’s dive in!
🔹 What Is a CSV File?
A CSV file is a plain text file that stores tabular data—like a spreadsheet—where each row is a line and each value is separated by a comma.
Example of a CSV file:
name,age,city
Alice,25,New York
Bob,30,London
Carol,22,São Paulo
CSV files are lightweight, easy to generate, and compatible with almost any spreadsheet software like Excel or Google Sheets.
📖 Reading a CSV File Using Python’s Built-in csv Module
Python includes a built-in module called csv that allows you to read CSV files easily.
Example:
import csv
with open('data.csv', newline='') as file:
reader = csv.reader(file)
for row in reader:
print(row)
Output:
['name', 'age', 'city']
['Alice', '25', 'New York']
['Bob', '30', 'London']
['Carol', '22', 'São Paulo']
💡 Tip: Use newline='' to prevent extra blank lines when reading files on Windows.
✏️ Writing to a CSV File with csv.writer
Writing to a CSV file is just as simple:
import csv
data = [
['name', 'age', 'city'],
['Alice', 25, 'New York'],
['Bob', 30, 'London'],
['Carol', 22, 'São Paulo']
]
with open('data.csv', mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
This will create (or overwrite) a file called data.csv with the content above.
🐼 Reading CSV Files with pandas
While csv is great for small tasks, pandas is the go-to library for working with larger or more complex datasets.
import pandas as pd
df = pd.read_csv('data.csv')
print(df)
Output:
pgsql
CopiarEditar
name age city
0 Alice 25 New York
1 Bob 30 London
2 Carol 22 São Paulo
You can also access specific columns or rows easily:
python
CopiarEditar
print(df['name']) # prints the "name" column
print(df.iloc[0]) # prints the first row
🚫 Common Mistakes to Avoid
Forgetting newline='' on Windows: This can lead to blank lines between rows.
Not using mode='w' or mode='a': Always specify the mode when opening a file for writing.
Not handling headers: Remember to write headers manually with the csv module.
Not using try-except blocks: Always handle file-related errors gracefully.
📌 Summary
By now, you should feel confident in:
Opening and reading a CSV file with both csv and pandas
Writing your own CSV files from Python data structures
Avoiding common beginner pitfalls
CSV files are often the first step in learning how to process real-world data. Once you're comfortable here, you're ready to move on to topics like data visualization, data cleaning, and working with APIs.