Convert csv into tsv using pandas with escapechar

Viewed 2229

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"
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
Related