Skip to main content

CSV Basics

CSV (Comma-Separated Values) is one of the most common file formats in the world. When you download data from a bank statement, Google Sheets, or a government data portal, it often comes as a .csv file.


What Does a CSV File Look Like?

Name,Age,City
Rahul,22,Hyderabad
Priya,20,Bangalore
Sai,23,Vizag

Each line is a row. Values within a row are separated by commas. The first row is usually the header.


Reading CSV Files

Python has a built-in csv module (no installation needed):

import csv

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

for row in reader:
print(row)
# Output:
# ['Name', 'Age', 'City']
# ['Rahul', '22', 'Hyderabad']
# ['Priya', '20', 'Bangalore']
# ['Sai', '23', 'Vizag']

Each row is returned as a list of strings.


Writing CSV Files

import csv

students = [
["Name", "Age", "City"],
["Rahul", 22, "Hyderabad"],
["Priya", 20, "Bangalore"],
["Sai", 23, "Vizag"]
]

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

print("CSV file created!")
Why newline=""?

On Windows, without newline="", Python adds extra blank lines between rows. This parameter prevents that.


Reading CSV as Dictionaries

For easier access by column name, use DictReader:

import csv

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

for row in reader:
print(f"{row['Name']} is from {row['City']}")
# Output:
# Rahul is from Hyderabad
# Priya is from Bangalore
# Sai is from Vizag

Quick Summary

  • CSV Format: Comma-Separated Values for storing tabular datasets.
  • csv.reader(file): Reads rows as lists of string values.
  • csv.DictReader(file): Reads rows as dictionaries using the header line for keys.
  • csv.writer(file) & writerow(): Writes list rows to disk.
  • Windows Formatting: Always pass newline='' to open() when writing CSVs on Windows to avoid unwanted blank rows.

What's Next?

Now that you can work with text and CSV files, let's learn how to process web and AI data in Module 15b: JSON!