【问题标题】:python csv to tsv: in case record has comma insidepython csv to tsv:如果记录里面有逗号
【发布时间】:2018-04-13 11:14:12
【问题描述】:

我正在尝试将 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"

有什么方法可以在不影响字符串内逗号的情况下转换成tsv?

【问题讨论】:

标签: python csv


【解决方案1】:

尝试关注,csv 模块应该注意内联逗号。

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

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

在我们直接调用构造函数的地方使用file,您可以使用open,这是documentation here的首选方式。 结果是一样的。

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

结果

【讨论】:

  • file('output.tsv', 'w+')open('output.tsv', 'w+') ?
  • 两者都是可行的。 open 根据此处的文档在内部调用 filedocs.python.org/2/library/functions.html#file。然而,open 是受欢迎的首选方式。
  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2021-05-18
  • 1970-01-01
  • 2017-08-28
  • 1970-01-01
  • 2017-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多