A CSV (Comma-Separated Values) file is used to store tabular data such as spreadsheets and databases.
Each line represents a row, and values are separated by commas.
Python provides a built-in csv module to work with CSV files easily.
IMPORTING CSV MODULE
import csv
READING A CSV FILE
Example CSV File (data.csv)
Name,Age,City
Hira,25,Karachi
Ali,30,Lahore
Sara,22,Islamabad
Reading CSV File
import csvwith open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Each row is returned as a list.
SKIPPING HEADER ROW
import csvwith open("data.csv", "r") as file:
reader = csv.reader(file)
next(reader) # Skip header
for row in reader:
print(row)
USING DICTREADER
DictReader reads CSV data as dictionaries.
import csvwith open("data.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["Name"], row["Age"])
This makes it easier to access columns by name.
WRITING TO A CSV FILE
import csvwith open("new_data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "City"])
writer.writerow(["Hira", 25, "Karachi"])
writer.writerow(["Ali", 30, "Lahore"])
newline="" prevents extra blank lines on some systems.
WRITING USING DICTWRITER
import csvdata = [
{"Name": "Hira", "Age": 25, "City": "Karachi"},
{"Name": "Ali", "Age": 30, "City": "Lahore"}
]with open("dict_data.csv", "w", newline="") as file:
fieldnames = ["Name", "Age", "City"]
writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writeheader()
writer.writerows(data)
APPENDING TO A CSV FILE
import csvwith open("data.csv", "a", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Sara", 22, "Islamabad"])
IMPORTANT POINTS
• Always use with to handle files safely
• Use newline="" when writing CSV files
• Use DictReader and DictWriter for better readability
• CSV files store data in plain text format
WHY CSV FILES ARE IMPORTANT
• Common format for data exchange
• Used in Excel and databases
• Essential for data analysis
• Widely used in business and automation
Understanding how to work with CSV files is essential for handling structured data in Python applications.