当我运行此输入(保存为变量'line')时:
xsc_i,202,"House of Night",21,"/21_202"
通过csv阅读器:
for row in csv.reader(line): print row
它会分割字符串,而不仅仅是字段
['x'] ['s'] ['c'] ['_'] ['i'] ['', ''] ['2'] ['0'] ['2'] ['', '']
等等
即使我明确设置了分隔符,它也会出现此行为:
csv.reader(line, delimiter=",")
它甚至将字符串视为数组,但我无法弄清楚为什么,我不能只用逗号分割,因为许多逗号都在输入中的""字符串中.
Python 2.7,如果重要的话.
第一个参数将csv.reader()
是一个包含csv行的可迭代对象.在您的情况下,输入是一个包含单行的字符串(也是可迭代的).您需要将其括在line
一个列表中:
for row in csv.reader([line]): print row
演示:
>>> import csv >>> line = 'xsc_i,202,"House of Night",21,"/21_202"' >>> for row in csv.reader([line]): ... print row ... ['xsc_i', '202', 'House of Night', '21', '/21_202']