Python解析CSV忽略带双引号的逗号 [英] Python parse CSV ignoring comma with double-quotes
本文介绍了Python解析CSV忽略带双引号的逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含如下行的 CSV 文件:
I have a CSV file with lines like this:
"AAA", "BBB", "Test, Test", "CCC"
"111", "222, 333", "XXX", "YYY, ZZZ"
等等......
我不想解析双引号下的逗号.IE.我的预期结果应该是
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']
这篇关于Python解析CSV忽略带双引号的逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文