Python Pandas data frame csv how to escape special chars

Viewed 81

I want to dump some sql results into tab limited file using pandas data frame. I am trying to use delimiter to delimit the tabs and quotes in the file. But it doesn't seems to be working. The working code I tried is as below:

import pandas as pd
import csv

# creating a DataFrame
items = {'Items': ['Number   one', 'Number   2'],
            'dept': ['["Books", "Generic", "Music"]', '["Books", "Generic", "Cooking"]']}
df = pd.DataFrame(items,
                  columns =['Items','dept'])
# saving as a CSV file
df.to_csv('Items.csv', sep ='\t', quoting=csv.QUOTE_NONE, escapechar='\\') 

The output I got is as below:

0       Number   one    ["Books", "Generic", "Music"]
1       Number   2      ["Books", "Generic", "Cooking"]

But expected output is as below.

0       Number\   one    [\"Books\", \"Generic\", \"Music\"]
1       Number\   2      [\"Books\", \"Generic\", \"Cooking\"]

I want to delimit the tab spaces in string "Number one" and quotes in ["Books", "Generic", "Music"]

It was working with normal CSV writer with below code:

csv.writer(fp, delimiter='\t', quoting=csv.QUOTE_NONE, escapechar='\\')

What am I doing wrong? Appreciate any help

Thanks

0 Answers
Related