CSV stands for Comma-Separated Values. A CSV file is a simple text file used to store tabular data such as student records, employee information, product details, and marks.
A CSV file stores data in rows and columns. Each row represents a record and values in a row are normally separated by commas.
Example:
Here, the first row contains column headings and the following rows contain data.
CSV files normally use the .csv extension.
CSV files can be opened using applications such as Microsoft Excel, Google Sheets, or a text editor.
Python provides the csv module as part of its standard library. We can import it using the import statement.
import csv
After importing the module, we can use its functions and classes for working with CSV files.
The csv.reader() function is used to read rows from a CSV file.
import csv
with open("students.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Each row is returned as a list.
Suppose students.csv contains:
Name,Age,City Rahul,20,Patna Amit,22,Delhi Priya,21,Jaipur
Python code:
import csv
with open("students.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Output:
['Name', 'Age', 'City'] ['Rahul', '20', 'Patna'] ['Amit', '22', 'Delhi'] ['Priya', '21', 'Jaipur']
Sometimes we want to process only the data and skip the column headings.
import csv
with open("students.csv", "r") as file:
reader = csv.reader(file)
next(reader)
for row in reader:
print(row)
The next() function moves the reader to the next row. In this example, it skips the first row.
Each row returned by csv.reader() is a list, so we can access individual values using indexes.
import csv
with open("students.csv", "r") as file:
reader = csv.reader(file)
next(reader)
for row in reader:
print("Name:", row[0])
print("Age:", row[1])
print("City:", row[2])
The DictReader class reads each CSV row as a dictionary. The column headings are used as dictionary keys.
import csv
with open("students.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["Name"])
print(row["City"])
This can make the code easier to understand because we can use column names instead of numeric indexes.
The csv.writer() function is used to write data to a CSV file.
import csv
with open("students.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "City"])
writer.writerow(["Rahul", 20, "Patna"])
writer.writerow(["Amit", 22, "Delhi"])
writer.writerow(["Priya", 21, "Jaipur"])
When writing CSV files, using newline="" helps prevent unwanted blank lines on some platforms.
with open("students.csv", "w", newline="") as file:
writer = csv.writer(file)
It is a common practice when using Python's CSV writer.
The writerow() method writes one row to a CSV file.
import csv
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["Rahul", 20])
The writerows() method writes multiple rows at once.
import csv
data = [
["Rahul", 20],
["Amit", 22],
["Priya", 21]
]
with open("students.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerows(data)
The DictWriter class is used to write dictionaries to a CSV file.
import csv
with open("students.csv", "w", newline="") as file:
fields = ["Name", "Age", "City"]
writer = csv.DictWriter(file, fieldnames=fields)
writer.writeheader()
writer.writerow({
"Name": "Rahul",
"Age": 20,
"City": "Patna"
})
writer.writerow({
"Name": "Amit",
"Age": 22,
"City": "Delhi"
})
The writeheader() method writes the field names as the first row of a CSV file.
fields = ["Name", "Age", "City"]
writer = csv.DictWriter(
file,
fieldnames=fields
)
writer.writeheader()
A delimiter is the character used to separate values. The default delimiter for csv.reader() and csv.writer() is a comma.
We can use another delimiter, such as a semicolon.
import csv
with open("data.csv", "r") as file:
reader = csv.reader(file, delimiter=";")
for row in reader:
print(row)
Use the a mode when you want to add new rows without deleting existing data.
import csv
with open("students.csv", "a", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Neha", 23, "Mumbai"])
The new row is added at the end of the file.
We can create a CSV file directly from a list of lists.
import csv
students = [
["Name", "Age", "Course"],
["Rahul", 20, "Python"],
["Amit", 22, "Java"],
["Priya", 21, "SQL"]
]
with open("students.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(students)
import csv
students = [
{
"name": "Rahul",
"age": 20,
"course": "Python"
},
{
"name": "Amit",
"age": 22,
"course": "Java"
}
]
with open("students.csv", "w", newline="") as file:
fields = ["name", "age", "course"]
writer = csv.DictWriter(
file,
fieldnames=fields
)
writer.writeheader()
writer.writerows(students)
CSV data may contain commas or other special characters inside values. The CSV module provides quoting options to handle such data correctly.
import csv
with open("data.csv", "w", newline="") as file:
writer = csv.writer(
file,
quoting=csv.QUOTE_ALL
)
writer.writerow(["Rahul", "Patna"])
The QUOTE_ALL option places quotes around all fields.
The following program reads student records from a CSV file and displays each student's information.
import csv
with open("students.csv", "r") as file:
reader = csv.DictReader(file)
for student in reader:
print("Name:", student["Name"])
print("Age:", student["Age"])
print("City:", student["City"])
print("----------------")
import csv
students = [
["Rahul", 20, "Patna"],
["Amit", 22, "Delhi"],
["Priya", 21, "Jaipur"]
]
# Write data
with open("students.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "City"])
writer.writerows(students)
# Read data
with open("students.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
This example first creates a CSV file and then reads the data from it.
| Tool | Purpose |
|---|---|
| csv.reader() | Reads CSV rows |
| csv.writer() | Writes CSV rows |
| csv.DictReader() | Reads CSV rows as dictionaries |
| csv.DictWriter() | Writes dictionaries to CSV |
| writerow() | Writes one row |
| writerows() | Writes multiple rows |
| writeheader() | Writes dictionary field names as a header |
Question: Which Python function is commonly used to read rows from a CSV file?