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
benefitsThe 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.
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.
string
values—it can be used like any other list.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']
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.
sniff()
is then passed to the reader initialization method.class
stores information about the delimiter characters and how the file is formatted. We then use the reader.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']
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.