Csv.reader () split values ​​by individual characters

I have the following code trying to iterate over some elements:

Here is the input (Single line)

operations, s, item_name, UPC, EAN, BRAND_NAME

   filename=open("WebstoreItemTemplate.csv").read()
   template=csv.reader(filename,delimiter=',')
   for row in template:
        print row

      

I expect the output to look the same as:

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

      

instead, I get the following output: each letter is treated like a list. I have verified that the file is in csv format, so I'm not sure what I am doing wrong.

['o']
['p']
['e']
['r']
['a']
['t']
['i']
['o']
['n']
['', '']
['s']
['k']
['u']
['', '']
['i']
['t']
['e']
['m']
['_']
['n']
['a']
['m']
['e']
['', '']
['u']
['p']
['c']
['', '']
['e']
['a']
['n']
['', '']
['b']
['r']
['a']
['n']
['d']
['_']
['n']
['a']
['m']
['e']

      

+3


source to share


1 answer


Remove .read

and just pass the file object:

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

      

What will give you:

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

      

From the docs :



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

Returns a reader object that will iterate over the lines in the given csvfile. csvfile can be any object that supports the iterator protocol and returns a string each time the next () method is called - both file objects and list objects.

This basically happens:

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

      

+6


source







All Articles