Python CSV: csv.reader and Sniffer

Use the csv module to read comma separated values files. Call csv.reader and use Sniffer.

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. It can sniff the format of a file. We test this helpful type.

Example. We first open a file in a "with" statement. The syntax to do this is a little different but straightforward. Then we call csv.reader, which creates a reader. We specify here that the delimiter is a comma.

Tip: The reader can then be looped over. Each row is a list of string values. It can be used like any other list.

Delimiter: This must be a 1-character string. In my testing, a TypeError is encountered if a different length is specified.

Input file.csv one,two,three,4 cat,dog,mouse,5 Python program that uses CSV file 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) Output ['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. We call the sniff method to generate a dialect.

The dialect returned by sniff() is then passed to the reader initialization method. 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.

Python program that uses Sniffer 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( # Seek to beginning. # Read file and print its rows. r = csv.reader(f, dialect) for row in r: print(row) Output ['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.CSV:

Summary. A powerful CSV file parser is not always needed in programs. Often the format is well-known. But when more features are required, csv.reader and its dialect class are helpful. They make programs easier to develop.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to