Python CSV Module: Reference and Examples
Last updated:Table of Contents
Read CSV file line by line
import csv
with open("path/to/file.csv") as f:
reader = csv.reader(f)
for line in reader:
# line is an array of strings
You can provide extra options, too. If you have a line like this:
"16","foo bar, baz","foo, bar \"...\" baz...", "foo,bar, baz"
You need to instruct the reader to disconsider commas within double quotes and to use '\'
to escape double quotes when inside a double-quoted block. You also need to tell it to disregard empty spaces before doublw quotes:
with open("path/to/file.csv",'r') as f:
reader = csv.reader(f,quotechar='"', delimiter=',', escapechar='\\', skipinitialspace=True)
for line in reader:
# line is an array of strings
Write CSV file using DictWriter
import csv
path_to_output_file = "my-file.csv"
with open(path_to_output_file, "w") as fout:
# create a writer object and name the columns
csv_writer = csv.DictWriter(fout,
fieldnames=["id","name"],
escapechar='\\', # escape double quotes using a single backslash
doublequote=False, # don't duplicate every double quote
quoting=csv.QUOTE_ALL) # wrap every value in double quotes, for safety
# optional: write a header
csv_writer.writeheader()
# now write a line at a time
csv_writer.writerow({'id':0, 'name': 'john'})
csv_writer.writerow({'id':1, 'name': 'mary'})
UnicodeDecodeError
Make sure you set encoding="utf-8"
:
import csv
with open("path/to/file.csv", encoding="utf-8") as f:
reader = csv.reader(f)
for line in reader:
# line is an array of strings
Skip Header Line
Use method next(<file_pointer>)
before creating the CSV reader:
import csv
with open("path/to/file.csv") as f:
# skip the first line
next(f)
reader = csv.reader(f)
for line in reader:
# line is an array of strings