How Python reads, writes, and processes spreadsheet-style data
CSV and Excel files are among the most common formats for storing structured data. Python provides powerful tools for reading, writing, and manipulating these files, making it ideal for data analysis, automation, and reporting.
CSV (Comma-Separated Values) files store data in plain text. Python’s built‑in csv module makes them easy to handle.
import csv
with open("data.csv") as file:
reader = csv.reader(file)
for row in reader:
print(row)
import csv
rows = [
["Name", "Age"],
["Alice", 30],
["Bob", 25]
]
with open("output.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(rows)
These classes treat each row as a dictionary:
import csv
with open("data.csv") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["Name"], row["Age"])
Excel files (.xlsx) require external libraries. The most common is openpyxl.
pip install openpyxl
from openpyxl import load_workbook
wb = load_workbook("data.xlsx")
sheet = wb.active
for row in sheet.iter_rows(values_only=True):
print(row)
from openpyxl import Workbook
wb = Workbook()
sheet = wb.active
sheet["A1"] = "Name"
sheet["B1"] = "Age"
sheet.append(["Alice", 30])
sheet.append(["Bob", 25])
wb.save("output.xlsx")
pandas is the most powerful tool for working with tabular data.
import pandas as pd
df = pd.read_csv("data.csv")
print(df)
df = pd.read_excel("data.xlsx")
print(df)
df.to_csv("output.csv", index=False)
df.to_excel("output.xlsx", index=False)
Now that you can work with CSV and Excel files, you're ready to explore data visualization in Lesson 26: Introduction to Data Visualization (matplotlib).
← Back to Lesson Index