Last Updated : 15 Jul, 2025
CSV (Comma Separated Values) format is one of the most widely used formats for storing and exchanging structured data between different applications, including databases and spreadsheets. CSV files store tabular data, where each data field is separated by a delimiter, typically a comma. Python provides built-in support for handling CSV files through the csv module, making it easy to read, write and manipulate CSV data efficiently.
However, we first need to import the module using:
Reading a CSV File in Pythonimport csv
To read a CSV file, Python provides the csv.reader class, which reads data in a structured format. The first step involves opening the CSV file using the open() function in read mode ('r'). The csv.reader() function then reads the file, returning an iterable reader object.
Example CSV File: Giants.csv
.CSV file Syntax:Parameters:csv.reader(csvfile, dialect='excel', **fmtparams)
Example:
Python
import csv
# Opening the CSV file
with open('Giants.csv', mode='r') as file:
# Reading the CSV file
csvFile = csv.reader(file)
# Skipping the header (uncomment if needed)
# next(csvFile)
# Displaying the contents of the CSV file
for line in csvFile:
print(line)
Output
['Steve', 13, 'A']
['John', 14, 'F']
['Nancy', 14, 'C']
['Ravi', 13, 'B']
Explanation: The csv module reads Giants.csv using csv.reader(file), iterating row by row. The with statement ensures proper file closure. Each row is returned as a list of column values. Use next(csvFile) to skip the header.
Writing to a csv file in pythonPython provides the csv.writer class to write data to a CSV file. It converts user data into delimited strings before writing them to a file. While opening the file, using newline='' prevents unnecessary newlines when writing.
Syntax:Parameters:csv.writer(csvfile, dialect='excel', **fmtparams)
Writing multiple rows:writerow(fields)
writerows(rows)
Example:
Python
import csv
# Field names
f = ['Name', 'Branch', 'Year', 'CGPA']
# Data rows of CSV file
r = [
['Nikhil', 'COE', '2', '9.0'],
['Sanchit', 'COE', '2', '9.1'],
['Aditya', 'IT', '2', '9.3'],
['Sagar', 'SE', '1', '9.5'],
['Prateek', 'MCE', '3', '7.8'],
['Sahil', 'EP', '2', '9.1']
]
# Name of the CSV file
fn = "university_records.csv"
# Writing to CSV file
with open(fn, 'w', newline='') as csvfile:
# Creating a CSV writer object
csvwriter = csv.writer(csvfile)
# Writing the field names
csvwriter.writerow(f)
# Writing the data rows
csvwriter.writerows(r)
Output: A file named university_records.csv will be created containing the following data.
OutputExplanation: This example shows how to write a list of dictionaries to a CSV file using csv.DictWriter. Each dictionary is a student record, with fieldnames as column headers. The file is opened in write mode ('w'), writeheader() writes headers and writerows(d) writes records.
Writing a dictionary to a csv fileThe csv.DictWriter class allows writing a dictionary to a CSV file. It maps dictionary keys to field names.
Syntax:Parameters:csv.DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)
Example: A file named university_records.csv will be created containing the following data.
Python
import csv
# Data rows as dictionary objects
d = [
{'name': 'Nikhil', 'branch': 'COE', 'year': '2', 'cgpa': '9.0'},
{'name': 'Sanchit', 'branch': 'COE', 'year': '2', 'cgpa': '9.1'},
{'name': 'Aditya', 'branch': 'IT', 'year': '2', 'cgpa': '9.3'},
{'name': 'Sagar', 'branch': 'SE', 'year': '1', 'cgpa': '9.5'},
{'name': 'Prateek', 'branch': 'MCE', 'year': '3', 'cgpa': '7.8'},
{'name': 'Sahil', 'branch': 'EP', 'year': '2', 'cgpa': '9.1'}
]
# Field names
f = ['Name', 'Branch', 'Year', 'CGPA']
# Name of the CSV file
fn = "university_records.csv"
# Writing to CSV file
with open(fn, 'w', newline='') as csvfile:
# Creating a CSV DictWriter object
writer = csv.DictWriter(csvfile, fieldnames=f)
# Writing headers (field names)
writer.writeheader()
# Writing data rows
writer.writerows(d)
Output
OutputExplanation: This example demonstrates writing a list of student records to a CSV file using csv.DictWriter. The file is opened in write mode ('w'), fieldnames define column headers, writeheader() writes them and writerows(d) adds records. Keys must match fieldnames to ensure alignment.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4