如何使用Python在csv中为字符串添加双引号

时间:2016-01-07 09:26:36

标签: python csv

我在CSV文件中设置了数据,我想在文本和字母数字数据中添加双引号,其余的整数,浮点数和小数不是双引号。

任何人都可以帮忙吗?

示例数据:

1, 3434, 789459 ,bdgvdjhjdhf, nagesd232 ,2yuyfudyf, #123 abc calony bangalore 

预期结果将是:

1, 3434, 789459 ,"bdgvdjhjdhf", "nagesd232" ,"2yuyfudyf", "#123 abc calony bangalore" 

3 个答案:

答案 0 :(得分:2)

您可以使用Python的csv模块,如下所示:

import csv

with open('input.csv', newline='') as f_input, open('output.csv', 'w', newline='') as f_output:

    csv_input = csv.reader(f_input, skipinitialspace=True)
    csv_output = csv.writer(f_output, quoting=csv.QUOTE_NONNUMERIC)

    for row_input in csv_input:
        row_output = []
        for col in row_input:
            try:
                row_output.append(int(col))
            except ValueError, e:
                row_output.append(col)

        csv_output.writerow(row_output)

这会从input.csv读取每一行,并尝试转换int中的每个条目。如果失败则将其存储为字符串。然后将每一行写入output.csv,提供以下类型的输出:

1,3434,789459,"bdgvdjhjdhf","nagesd232 ","2yuyfudyf","#123 abc calony bangalore"

如果您的csv还包含float格式的列,则可以使用以下方法:

import csv

with open('input.csv', newline='') as f_input, open('output.csv', 'w', newline='') as f_output:
    csv_input = csv.reader(f_input, skipinitialspace=True)
    csv_output = csv.writer(f_output, quoting=csv.QUOTE_NONNUMERIC)

    for row_input in csv_input:
        row_output = []
        for col in row_input:
            try:
                row_output.append(int(col))
            except ValueError, e:
                try:
                    row_output.append(float(col))
                except ValueError, e:
                    row_output.append(col)

        csv_output.writerow(row_output)

如果正在使用Python 2.x,请使用:

with open('input.csv', 'rb') as f_input, open('output.csv', 'wb') as f_output:

答案 1 :(得分:0)

input_data = '1, 3434, 789459 ,bdgvdjhjdhf, nagesd232 ,2yuyfudyf, #123 abc calony bangalore'
output = []
for i in input_data.split(','):
    i = i.strip()
    if not i.isnumeric():
        output.append('"%s"' % i)
    else:
        output.append(i)
print(', '.join(output))

答案 2 :(得分:0)

您可以查看哪个班级有您的任何值:

list_val = [1, 3434, 789459 ,bdgvdjhjdhf, nagesd232 ,2yuyfudyf, #123 abc calony bangalore]
for i in list_val:
    if i.__class__ = str:
    .....