csv.reader() is separating values by individual character

You just need to call splitlines() after calling read. Passing the file object is not always ideal or required.

For example reading from string:

import csv
rawdata = 'name,age\nDan,33\nBob,19\nSheri,42'
myreader = csv.reader(rawdata.splitlines())
for row in myreader:
    print(row[0], row[1])

in my case I just wanted to detect encoding using chardet:

with open("WebstoreItemTemplate.csv") as f:
     raw_data = f.read()
     encoding = chardet.detect(raw_data)['encoding']
     cr = csv.reader(raw_data.decode(encoding).splitlines())
...

Here are some practical examples that I have personally found useful: http://2017.compciv.org/guide/topics/python-standard-library/csv.html


Remove the .read and just pass the file object:

with open("WebstoreItemTemplate.csv") as filename:
    template=csv.reader(filename)
    for row in template:
        print row

Which will give you:

['operation', 'sku', 'item_name', 'upc', 'ean', 'brand_name']

From the docs:

csv.reader(csvfile, dialect='excel', **fmtparams)

Return a reader object which will iterate over lines in the given csvfile. csvfile can be any object which supports the iterator protocol and returns a string each time its next() method is called — file objects and list objects are both suitable.

Basically this is happening:

In [9]: next(iter("foo"))
Out[9]: 'f'

Tags:

Python

Csv