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