Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert csv into tsv using pandas with escapechar

Tags:

python

pandas

csv

I have a sample csv file contains

col1
"hello \n
world"
"the quick \njump
\n \r \t brown fox"

Sample code convert into tsv

import pandas as pd
df = read_csv(r'a.csv')

df.to_csv('data.tsv', sep='\t', encoding='utf-8', escapechar='\n')

Expecting result will be

col1
"hello \n world"
"the quick \njump \n \r \t brown fox"

But the result woud be

col1
"hello \n
world"
"the quick \njump
\n \r \t brown fox"
like image 567
dwayneJohn Avatar asked Jul 10 '20 05:07

dwayneJohn


People also ask

How do I export from pandas to TSV?

How To Write Pandas DataFrame as TSV File? We can use Pandas' to_csv() function to write dataframe as Tab Separated Value or TSV file by specifying the argument for separator with sep=”\t”.

How do I convert TSV to pandas CSV?

TSV file can be converted into CSV file by reading one line of data at a time from TSV and replacing tab with comma using re library and writing into CSV file. We first open the TSV file from which we read data and then open the CSV file in which we write data.


1 Answers

Using the escapechar while reading the csv worked for me. But it skipping the double quotes when converting to tsv.

df = pd.read_csv(r'a.csv', escapechar='\n')

df.to_csv('data.tsv', sep='\t', encoding='utf-8', index=False)

Output:

col1
hello \nworld
the quick \njump\n \r \t brown fox
like image 180
deadshot Avatar answered Sep 18 '22 18:09

deadshot