如何用分号替换逗号而不是用引号替换逗号

时间:2016-04-26 16:11:55

标签: python bash csv groovy replace

我有类似以下CSV的内容:

"blah blah, foo bar", 1, 454, ok, eng
blah blah foo bar, 2, 21, ko, esp
...

我需要将字段之间的逗号替换为分号,以便我可以正确拆分CSV。但不要在quoutes里面。

我需要或正则表达一个小脚本(python,groovy,bash ......)来解决这个问题。

2 个答案:

答案 0 :(得分:2)

考虑使用Python的csv模块。演示:

from csv import reader, writer
with open('input.csv') as inp, open('output.csv', 'w') as out:
    writer(out, delimiter=';').writerows(reader(inp))

文件内容:

$ cat input.csv 
"blah blah, foo bar", 1, 454, ok, eng
blah blah foo bar, 2, 21, ko, esp
$ cat output.csv 
blah blah, foo bar; 1; 454; ok; eng
blah blah foo bar; 2; 21; ko; esp

答案 1 :(得分:1)

import csv

infile = open("inputfile.csv", "r")
outfile = open("outputfile.csv", "w")

csvReader = csv.reader(infile)

for line in csvReader:
    outfile.write(";".join(line) + "\n")

infile.close()
outfile.close()

在Python 2.7和3.5上测试

示例输出:

blah blah, foo bar; 1; 454; ok; eng
blah blah foo bar; 2; 21; ko; esp