Working with CSV Files in Python
CSV (Comma Separated Values) is a common format for tabular data, like what you’d see in spreadsheets or simple databases. Python’s built-in csv module makes it straightforward to read from and write to CSV files without having to manually split strings.
Import the CSV Module
import csv
Reading CSV Files
To read a CSV, you typically:
- Open the file with
open()in text mode ('r'for read). - Create a
csv.readerobject using that file. - Loop through the reader to get rows (as lists of values).
Example – Reading a CSV file Assume students.csv contains:
Name,Age,Grade
Alice,14,A
Bob,15,B
Charlie,14,C
file = open('students.csv', 'r')
csv_reader = csv.reader(file)
# If the CSV has a header and we want to skip it:
# header = next(csv_reader) # uncomment to skip the first line
for row in csv_reader:
print(row)
file.close()
Output:
['Alice', '14', 'A']
['Bob', '15', 'B']
['Charlie', '14', 'C']
- Each row is a list of strings.
csv.readerhandles splitting at commas and managing quotes.- Skip the header with
next(csv_reader)if needed.
Using csv.DictReader
Returns each row as a dictionary, using the header row as keys:
file = open('students.csv', 'r')
dict_reader = csv.DictReader(file)
for row in dict_reader:
print(row["Name"], "is", row["Age"], "years old.")
file.close()
Output Example:
Alice is 14 years old.
Writing CSV Files
To write data to CSV:
- Open the file in write mode.
- Create a
csv.writerobject. - Use
writer.writerow()for single rows orwriter.writerows()for multiple rows.
Important: When writing CSV on Windows, pass newline='' to open() to avoid extra blank lines. Example – Writing CSV data:
data = [
["Name", "Branch", "Year", "CGPA"], # header
["Nikhil", "COE", "2", "9.0"],
["Sanchit", "COE", "2", "9.1"],
["Aditya", "IT", "2", "9.3"],
]
csvfile = open('university_records.csv', 'w', newline='')
csv_writer = csv.writer(csvfile)
for row in data:
csv_writer.writerow(row)
csvfile.close()
# Equivalent code using Write Rows
csvfile = open('university_records.csv', 'w', newline='')
csv_writer = csv.writer(csvfile)
csv_writer.writerows(data)
csvfile.close()
Equivalent using writer.writerows():
csvfile = open('university_records.csv', 'a', newline='')
csv_writer = csv.writer(csvfile)
csv_writer.writerows(data)
csvfile.close()
Using csv.DictWriter
Similar to reading, you can write using dictionaries.
fieldnames = ["Name", "Branch", "Year", "CGPA"]
rows = [
{"Name": "Nikhil", "Branch": "COE", "Year": "2", "CGPA": "9.0"},
{"Name": "Sanchit", "Branch": "COE", "Year": "2", "CGPA": "9.1"},
]
csvfile = open('university_records.csv', 'w', newline='')
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader() # write the header row
writer.writerows(rows) # write all rows from the list of dicts
csvfile.close()
- Each dictionary’s keys match the
fieldnames. writeheader()writes the header row automatically.
CSV Dialects & Delimiters
By default:
- Separator: comma
- Quoting: automatic when needed
- Dialect:
"excel"
If your file uses a different delimiter:
csv_reader = csv.reader(file, delimiter=';')
csv_writer = csv.writer(csvfile, delimiter='t')
Summary:
- Use
csv.reader/csv.writerfor basic reading/writing. - Always use
newline=''when writing. - For named access, use
DictReader/DictWriter. csvhandles quoting, newlines, and delimiters automatically.
