【问题标题】:How to escape comma in string Python 2.7 in a .csv file如何在 .csv 文件中转义字符串 Python 2.7 中的逗号
【发布时间】:2016-09-10 05:15:16
【问题描述】:

我在 .csv 文件中有一个字符串 ven = "the big bad, string"。我需要使用 Python 2.7 转义 , 字符。

目前我正在这样做:ven = "the big bad\, string",但是当我运行以下命令print ven 时,它会在终端中打印the big bad\, string

如何有效地从 .csv 文件中的此字符串中转义 , 字符,这样如果有人要 dl 该文件并在 excel 中打开它就不会搞砸一切?

【问题讨论】:

  • 您是使用import csv,还是手动构建csv文件?
  • @Robᵩ 手动构建它们。要撤消它并使用 import csv 需要做很多工作。 ://
  • 为什么投反对票?什么给了?
  • 另外,您的问题并不清楚您是阅读 CSV 文件还是构建 CSV 文件。 ven = 是否存在于 CSV 文件中或仅存在于您的代码中。请阅读minimal reproducible example 并考虑创建一个简短、完整的示例程序来说明问题。

标签: python string python-2.7 csv escaping


【解决方案1】:

假设您使用的是the csv module,您无需执行任何操作。 csv为你处理:

import csv

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

结果:

1,a,"the big bad, string"

但是,如果您没有使用 import csv,那么您需要引用该字段:

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

结果:

"1","a","the big bad, string"

【讨论】:

  • 谢谢。这很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-04
  • 1970-01-01
  • 1970-01-01
  • 2019-07-12
  • 2017-11-30
  • 2019-12-26
相关资源
最近更新 更多