Python解析CSV忽略带有双引号的逗号 [英] Python parse CSV ignoring comma with double-quotes

查看:1423
本文介绍了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']

这篇关于Python解析CSV忽略带有双引号的逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆