Python用字符串中的引号括起来

时间:2014-04-21 15:59:37

标签: python string csv

对于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")

不确定接下来会做什么。

1 个答案:

答案 0 :(得分: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)