Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape comma in string Python 2.7 in a .csv file

I have a string ven = "the big bad, string" in a .csv file. I need to escape the , character using Python 2.7.

Currently I am doing this: ven = "the big bad\, string", but when I run the following command print ven, it prints the big bad\, string in the terminal.

How do I effectively escape the , character from this string within a .csv file so if someone were to dl that file and open it in excel it wouldn't screw everything up?

like image 912
Erik Åsland Avatar asked Mar 24 '26 23:03

Erik Åsland


1 Answers

Assuming that you're using the csv module, you don't have to do anything. csv deals with it for you:

import csv

w = csv.writer(open("result.csv","w"))
w.writerow([1,"a","the big bad, string"])

result:

1,a,"the big bad, string"

If, however, you aren't using import csv, then you'll want to quote that field:

row = [1, "a", "the big bad, string"]
print ','.join('"%s"'%i for i in row)

Result:

"1","a","the big bad, string"
like image 193
Robᵩ Avatar answered Mar 27 '26 14:03

Robᵩ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!