jxn
jxn

Reputation: 8025

Python Pandas: How to replace to_csv string quoting from double quotes to single quotes

I have a dataframe where one of the column(col2) has many commas hence when pandas output to a CSV file, it by defaults encloses that field value in double quotes. How do i specify that i want single quotes for columns with commas?

df:

col1  col2     col3
1    x;y,b;c  blabla

df.to_csv('myfile.csv')

current CSV file:

col1,col2,col3
 1,"x;y,b;c",blabla

I want single quotes instead:

col1,col2,col3
 1,'x;y,b;c',blabla

Upvotes: 0

Views: 3932

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210842

you can use quotechar="'" parameter:

In [41]: df
Out[41]:
   col1     col2    col3
0     1  x;y,b;c  blabla

In [42]: print(df.to_csv(index=False, quotechar="'"))
col1,col2,col3
1,'x;y,b;c',blabla

Upvotes: 1

Related Questions