Dup Ver Goto 📝

Basic Python CSV

PT2/lang/python/library/csv python csv does not exist
To
42 lines, 105 words, 811 chars Page 'BasicPythonCsv' does not exist.

Read the docs here.

Reading

From file

import csv

data = []
with open(filename) as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        data.append(row)

From string

Use StringIO

from io import StringIO
import csv

scsv = """text,with,Polish,non-Latin,letters
1,2,3,4,5,6
a,b,c,d,e,f
gęś,zółty,wąż,idzie,wąską,dróżką,
"""

f = StringIO(scsv)
reader = csv.reader(f, delimiter=',')
for row in reader:
    print('\t'.join(row))

Writing

Writing To File

import csv
data = [ [ "hello", "world" ], [ 1, 2 ], [ 3, 4 ], [ "need,quote", 'quote "quote"' ] ]
with open('out.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    for row in data:
        writer.writerow(row)