CSV Files
I keep a couple of utility functions under my pillow for reading and writing csv files:
import csv, os, io
# Read a csv file into a list of lists.
def read_csv(fnm):
= []
rows with io.open(fnm, newline='') as f:
= csv.reader(f)
reader for row in reader:
rows.append(row)return rows
# Write a list of lists to a csv file.
= [
lol 'size', 'color', 'angle'],
['5', 'green', '45'],
[ '6', 'orange', '50'],
[
]
# Writes a list of lists to a csv file. First list of the
# lol is the heading row.
def write_csv(fnm, lol):
with io.open(fnm, 'w', newline='') as f:
# You need this to get a regular non-DOS text file.
= csv.writer(f, lineterminator=os.linesep)
writer writer.writerows(lol)
If you leave out the lineterminator=os.linesep
on GNU/Linux you’ll get funny “\r\n” line-endings.