python csv 到 tsv:如果记录里面有逗号

Sop*_*e.K 0 python csv

我正在尝试将 csv 格式转换为 tsv。我只是用它来将逗号更改为制表符。

tsv = re.sub(',', '\t', csv)

但我无法处理里面有逗号的字符串,例如:

dept_no,dt,hello
1,20180411,hello its me
2,20180412,here has tab
3,20180412,"here, is, commas"
Run Code Online (Sandbox Code Playgroud)

有没有什么方法可以转换为 tsv 而不影响字符串内部的逗号?

Ani*_*l_M 6

尝试以下操作,csv 模块应该处理内联逗号。

import csv
csv.writer(file('output.tsv', 'w+'), delimiter='\t').writerows(csv.reader(open("input.csv"))) 
Run Code Online (Sandbox Code Playgroud)

EDIT-1
[根据讨论添加开放方法]

不再使用file我们直接调用构造函数的位置,您可以open根据此处的文档使用首选方式。结果是一样的。

csv.writer(open('output.tsv', 'w+'), delimiter='\t').writerows(csv.reader(open("input.csv")))
Run Code Online (Sandbox Code Playgroud)

结果 在此输入图像描述