我有以下代码试图迭代一些项目:
这是输入(单行)
操作中,SKU,ITEM_NAME,UPC,EAN,BRAND_NAME
filename=open("WebstoreItemTemplate.csv").read()
template=csv.reader(filename,delimiter=',')
for row in template:
print row
我期待输出看起来像是:
['operation','sku','item_name','upc,ean','brand_name']
而是我收到以下输出,每个字母被视为一个列表。我已经验证该文件是csv格式的,所以我不确定我做错了什么。
['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']
答案 0 :(得分:10)
删除.read
并传递文件对象:
with open("WebstoreItemTemplate.csv") as filename:
template=csv.reader(filename)
for row in template:
print row
哪个会给你:
['operation', 'sku', 'item_name', 'upc', 'ean', 'brand_name']
来自docs:
csv.reader(csvfile,dialect =' excel',** fmtparams)
返回一个读取器对象,它将迭代给定csvfile中的行。 csvfile可以是任何支持迭代器协议的对象,每次调用next()方法时都返回一个字符串 - 文件对象和列表对象都是合适的。
基本上这种情况正在发生:
In [9]: next(iter("foo"))
Out[9]: 'f'
答案 1 :(得分:1)
您只需要在调用read之后调用splitlines()
。传递文件对象并不总是理想或必需的。
例如从字符串中读取:
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])
就我而言,我只是想使用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())
...
以下是一些我个人认为有用的实用示例: http://2017.compciv.org/guide/topics/python-standard-library/csv.html