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"
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”.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With