Eri*_*and 3 python csv string escaping python-2.7
我ven = "the big bad, string"在 .csv 文件中有一个字符串。我需要,使用Python 2.7转义字符。
目前我正在这样做:ven = "the big bad\, string",但是当我运行以下命令时print ven,它会the big bad\, string在终端中打印。
我如何有效地,从.csv文件中的这个字符串中转义字符,这样如果有人要 dl 那个文件并在 excel 中打开它,它就不会搞砸一切?
假设您使用的是 csv 模块,则无需执行任何操作。csv为您处理:
import csv
w = csv.writer(open("result.csv","w"))
w.writerow([1,"a","the big bad, string"])
Run Code Online (Sandbox Code Playgroud)
结果:
import csv
w = csv.writer(open("result.csv","w"))
w.writerow([1,"a","the big bad, string"])
Run Code Online (Sandbox Code Playgroud)
但是,如果您没有使用import csv,那么您需要引用该字段:
row = [1, "a", "the big bad, string"]
print ','.join('"%s"'%i for i in row)
Run Code Online (Sandbox Code Playgroud)
结果:
1,a,"the big bad, string"
Run Code Online (Sandbox Code Playgroud)