- Python Features
- Python Installation
- PyCharm Configuration
- Python Variables
- Python Data Types
- Python If Else
- Python Loops
- Python Strings
- Python Lists
- Python Tuples
- Python List Vs Tuple
- Python Sets
- Python Dictionary
- Python Functions
- Python Files I/O
- Read Write Excel
- Read Write JSON
- Read Write CSV
- Python OS Module
- Python Exceptions
- Python Datetime
- Python Collection Module
- Python Sys Module
- Python Decorator
- Python Generators
- Python OOPS
- Python Numpy Module
- Python Pandas Module
- Python Sqlite Module
What is a CSV File?
CSV stands for Comma-Separated Values and is commonly used for tabular data like spreadsheets.
Python has a built-in csv module for handling CSV files.
import csv
Write to CSV File
Write Rows Manually
import csv
with open("students.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "City"]) # Header
writer.writerow(["Deepesh", 30, "Delhi"])
writer.writerow(["Riya", 25, "Mumbai"])
Write Multiple Rows (Loop / List)
import csv
data = [
["Name", "Age", "City"],
["Aman", 28, "Pune"],
["Neha", 24, "Chennai"],
["Kunal", 29, "Bangalore"]
]
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data) # write all rows at once
Read CSV File
Read and Print Entire File
import csv
with open("students.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Read CSV as Dictionary
💡 Best when the first row contains headers.
import csv
with open("students.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["Name"], row["City"])
Write CSV Using Dictionary
import csv
data = [
{"Name": "Raj", "Age": 27, "City": "Delhi"},
{"Name": "Simran", "Age": 23, "City": "Kolkata"}
]
with open("students_dict.csv", "w", newline="") as file:
fieldnames = ["Name", "Age", "City"]
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
Append to a CSV File
import csv
with open("students.csv", "a", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Kiran", 22, "Hyderabad"])
Handling Custom Delimiters
Example: Semi-colon ; separated file
import csv
with open("data_semicolon.csv", "r") as file:
reader = csv.reader(file, delimiter=";")
for row in reader:
print(row)
Real Example: CSV Filtering
Print only rows where Age > 25
import csv
with open("students.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
if int(row["Age"]) > 25:
print(row)
Summary
| Task | Method |
|---|---|
| Write row | writer.writerow() |
| Write multiple rows | writer.writerows() |
| Read CSV | csv.reader() |
| Read as dict | csv.DictReader() |
| Write dict | csv.DictWriter() |
| Append data | "a" mode |
| Change delimiter | delimiter=";" |