Python解析CSV忽略带有双引号的逗号
问题描述:
我有一个CSV文件,其中包含如下行:
I have a CSV file with lines like this:
"AAA", "BBB", "Test, Test", "CCC"
"111", "222, 333", "XXX", "YYY, ZZZ"
b $ b
等等...
and so on ...
我不想在双引号下解析逗号。即。我的预期结果应为
I dont want to parse comma's under double-quotes. ie. My expected result should be
AAA
BBB
Test, Test
CCC
我的代码:
import csv
with open('values.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print row
我试过在python下使用csv包,但没有运气。解析分解所有逗号。
I tried using csv package under python but no luck. The parses explodes all comma's.
请让我知道如果我遗漏了一些东西。
Please let me know if I'm missing something
答
这应该:
lines = '''"AAA", "BBB", "Test, Test", "CCC"
"111", "222, 333", "XXX", "YYY, ZZZ"'''.splitlines()
for l in csv.reader(lines, quotechar='"', delimiter=',',
quoting=csv.QUOTE_ALL, skipinitialspace=True):
print l
>>> ['AAA', 'BBB', 'Test, Test', 'CCC']
>>> ['111', '222, 333', 'XXX', 'YYY, ZZZ']