【问题标题】:Python Enclosing Words With Quotes In A StringPython 在字符串中用引号将单词括起来
【发布时间】:2014-04-21 15:59:36
【问题描述】:

对于 Python,我打开一个 csv 文件,如下所示:

    jamie,london,uk,600087
    matt,paris,fr,80092
    john,newyork,ny,80071

如何在 csv 文件中用引号将单词括起来,使其看起来像:

    "jamie","london","uk","600087"
    etc...

我现在拥有的只是基本的东西:

    filemame = "data.csv"
    file = open(filename, "r")

不知道接下来我会做什么。

【问题讨论】:

  • 你为什么要这样做?您要转换它吗?
  • 你现在拥有的几乎一无所有!我建议您查看csv 模块。
  • 我建议使用Python CSV library阅读数据。
  • 您应该使用 IO 写入模块,即 file = open(filename, "w")。

标签: python string csv


【解决方案1】:

如果您只是想转换文件,请使用csv module 中的QUOTE_ALL 常量,如下所示:

import csv

with open('data.csv') as input, open('out.csv','w') as output:
    reader = csv.reader(input)
    writer = csv.writer(output, delimiter=',', quoting=csv.QUOTE_ALL)
    for line in reader:
        writer.writerow(line)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    相关资源
    最近更新 更多