CSV. Reading CSV files is a common task. It can be accomplished in many ways: the split() method is often used. But the csv module provides more built-in support.
Module benefits. The CSV can sniff the format of a file. This can make python programs more robust and reliable—this can save us time. We test this helpful type.
Example. We first open a file in a "with" statement—the syntax to do this is straightforward. Then we call csv.reader, which creates a reader. We specify here that the delimiter is a comma.
Then The reader can be looped over. Each row is a list of string values—it can be used like any other list.
Note The delimiter must be a 1-character string. In my testing, a TypeError is encountered if a different length is specified.
import csv
# Open CSV file.
with open("C:/programs/file.csv", newline="") as f:
# Specify delimiter for reader.
r = csv.reader(f, delimiter=",")
# Loop over rows and display them.
for row in r:
print(row)one,two,three,4
cat,dog,mouse,5['one', 'two', 'three', '4']
['cat', 'dog', 'mouse', '5']
Sniffer. Sometimes a program may not know the format of the csv files. The delimiter characters may vary between files. With Sniffer, a class, we can handle this situation.
Info We call the sniff method to generate a dialect. The dialect returned by sniff() is then passed to the reader initialization method.
Also A dialect class stores information about the delimiter characters and how the file is formatted. We then use the reader.
Tip If you know the file format, you can pass a string literal to sniff() without reading a sample of the file.
import csv
# Open the file.
with open("C:/programs/file.csv") as f:
# Get dialect from Sniffer.# ... Pass a sample to sniff.
dialect = csv.Sniffer().sniff(f.read(1024))
# Seek to beginning.
f.seek(0)
# Read file and print its rows.
r = csv.reader(f, dialect)
for row in r:
print(row)['one', 'two', 'three', '4']
['cat', 'dog', 'mouse', '5']
Discussion. The csv module supports more than is shown on this page. It can also write CSV files. And it provides some features that are superior to using split() such as quote character support.
A CSV file parser is not always needed. But when complicated features are required, csv.reader and its dialect class are helpful. They make programs easier to develop.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 13, 2024 (edit).