C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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']
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(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)
Output
['one', 'two', 'three', '4']
['cat', 'dog', 'mouse', '5']