Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a .tsv to .csv?

Tags:

python

csv

tsv

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)

Gives me this error:

  File "tsv2csv.py", line 11, in <module>
    cw.writerows(filecontents)
_csv.Error: need to escape, but no escapechar set
like image 976
hannah Avatar asked Apr 20 '15 22:04

hannah


People also ask

Is TSV and CSV same?

The differences between TSV and CSV formats can be confusing. The obvious distinction is the default field delimiter: TSV uses TAB, CSV uses comma. Both use newline as the record delimiter. By itself, using different field delimiters is not especially significant.

How do I convert a tab-separated text to CSV?

Go to the File menu, choose 'Open CSV\Tab-Delimited File' (or simply press Ctrl+O), and then from the open dialog-box, choose the tab-delimited file to open. You can copy the tab-delimited string to the clipboard and then use the 'Open Text In Clipboard' option (Ctrl+F7).


2 Answers

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)

We can use the above code to convert the .tsv file to .csv file

like image 156
Terminator17 Avatar answered Oct 09 '22 12:10

Terminator17


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

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.

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

Example code:

# 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)
like image 23
Erik S Avatar answered Oct 09 '22 10:10

Erik S