如何将.tsv转换为.csv? [英] How do I convert a .tsv to .csv?

查看:2421
本文介绍了如何将.tsv转换为.csv?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试将.tsv转换为.csv.这个:

Trying to convert a .tsv to a .csv. This:

import csv

# read tab-delimited file
with open('DataS1_interactome.tsv','rb') as fin:
    cr = csv.reader(fin, delimiter='\t')
    filecontents = [line for line in cr]

# write comma-delimited file (comma is the default delimiter)
with open('interactome.csv','wb') as fou:
    cw = csv.writer(fou, quotechar='', quoting=csv.QUOTE_NONE)
    cw.writerows(filecontents)

给我这个错误:

  File "tsv2csv.py", line 11, in <module>
    cw.writerows(filecontents)
_csv.Error: need to escape, but no escapechar set

推荐答案

在尝试写入CSV文件时,它遇到一个令牌,该令牌必须在其中插入转义字符.但是,您尚未定义一个.

While attempting to write to the CSV file, it encounters a token where it has to insert an escape character. However, you have not defined one.

Dialect.escapechar

作者使用的一个单字符字符串进行转义 如果引用设置为QUOTE_NONE,则分隔符;如果quote设置为quote,则为quotechar 双引号是False.阅读时,escapechar删除所有特殊内容 含义来自以下字符.默认为无,即 禁用转义.

A one-character string used by the writer to escape the delimiter if quoting is set to QUOTE_NONE and the quotechar if doublequote is False. On reading, the escapechar removes any special meaning from the following character. It defaults to None, which disables escaping.

来源: https://docs.python.org/2/library/csv.html#csv.Dialect.escapechar

示例代码:

# write comma-delimited file (comma is the default delimiter)
with open('interactome.csv','wb') as fou:
    cw = csv.writer(fou, quotechar='', quoting=csv.QUOTE_NONE, escapechar='\\')
    cw.writerows(filecontents)

这篇关于如何将.tsv转换为.csv?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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