自定义Python CSV分隔符

时间:2012-05-12 02:31:52

标签: python csv

如何在双引号之间忽略逗号并删除不在双引号之间的逗号?

2 个答案:

答案 0 :(得分:3)

包含电池 - 只需使用Python附带的csv module

示例:

import csv

if __name__ == '__main__':
    file_path = r"/your/file/path/here.csv"
    file_handle = open(file_path, "r")
    csv_handle = csv.reader(file_handle)
    # Now you can work with the *values* in the csv file.

答案 1 :(得分:1)

为了您的兴趣,可以(大部分)使用正则表达式执行此操作;

mystr = 'No quotes,"Quotes",1.0,42,"String, with, quotes",1,2,3,"",,""'
import re
csv_field_regex = re.compile("""
(?:^|,)         # Lookbehind for start-of-string, or comma
(
    "[^"]*"     # If string is quoted: match everything up to next quote
    |
    [^,]*       # If string is unquoted: match everything up to the next comma
)
(?=$|,)         # Lookahead for end-of-string or comma
""", re.VERBOSE)

m = csv_field_regex.findall(mystr)

>>> pprint.pprint(m)
['No quotes',
 '"Quotes"',
 '1.0',
 '42',
 '"String, with, quotes"',
 '1',
 '2',
 '3',
 '""',
 '',
 '""']

这会处理除引号字符串中出现的转义引号之外的所有内容。也可以处理这种情况,但正则表达式变得更糟糕;这就是为什么我们有csv模块。