如何将.tsv转换为.csv?

2024-04-25 21:20:53 发布

您现在位置:Python中文网/ 问答频道 /正文

正在尝试将.tsv转换为.csv。这:

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

Tags: csvintsvaswithlineopenfile
3条回答

TSV是一种文件类型,其中的字段由制表符分隔。 如果要将TSV转换为CSV(逗号分隔值),只需进行查找并从TAB替换为COMMA

更新:
正如don-roby所指出的,“tsv中可能有逗号”,因为我们使用regex来转义由rfc4180定义的所有csv特殊字符。

即:

import re
tsv = open('tsv.tsv', 'r')
fileContent =  tsv.read()
appDesc = re.sub("""(?ism)(,|"|')""", r"\\\1", appDesc) # escape all especial charaters (" ' ,) rfc4180
fileContent = re.sub("\t", ",", fileContent) # convert from tab to comma
csv_file = open("csv.csv", "w")
csv_file.write(fileContent)
csv_file.close()
import pandas as pd 
tsv_file='name.tsv'
csv_table=pd.read_table(tsv_file,sep='\t')
csv_table.to_csv('new_name.csv',index=False)

我们可以使用上述代码将.tsv文件转换为.csv文件

尝试写入CSV文件时,遇到一个必须插入转义字符的标记。但是,您还没有定义一个。

Dialect.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)

相关问题 更多 >