As already mentioned by others, it is useful when you have quoted elements. But I'm going to show one another brilliant feature of CSV module.
What if you receive different files from somewhere else and you don't know which delimiters they used for separating the fields? You can't predict and also you don't want to implement a logic to parse all the possible delimiters when CSV module has Sniffer
class and has already implemented that for you.
sample:
line1|hey|20|40|50
line2|hey|20|40|50
line3|hey|20|40|50
line4|hey|20|40|50
line5|hey|20|50|60
line6|hey|20|50|60
...
code:
import csv
# The more you increase this value, the more accurate CSV can guess the dialect.
sample_bytes = 200
sniffer = csv.Sniffer()
with open('s.txt') as f:
dialect_object = sniffer.sniff(f.read(sample_bytes))
# to start from the beginning
f.seek(0)
reader = csv.reader(f, dialect=dialect_object)
for line in reader:
print(line)
output:
['line1', 'hey', '20', '40', '50']
['line2', 'hey', '20', '40', '50']
['line3', 'hey', '20', '40', '50']
['line4', 'hey', '20', '40', '50']
...