使字符串安全进行CSV编写?

时间:2018-08-01 17:33:59

标签: python csv export-to-csv

我需要使用打印语句写出到CSV文件,因此无法使用CSV编写器库。但是,正如预期的那样,逗号将字符串分成不同的列。如何在编写之前通过转换字符串来转义逗号?

例如:

my_str = 'I have apples, pears, and bannanas'
with open('test.csv','w', newline='') as out:
    print(my_str, file = out)

我需要这样的功能:

def csv_formatter(string):
    # transform string here 
    return csv_safe_string

我尝试按照其他帖子的建议将字符串括在引号中,但没有成功。

2 个答案:

答案 0 :(得分:4)

不要尝试模拟csv模块,只需将其与io.StringIO结合使用即可模拟文件输出:

import csv,io

def csv_formatter(string):
    outstream = io.StringIO()   # "fake" output file

    cw = csv.writer(outstream)  # pass the fake file to csv module
    cw.writerow([string])       # write a row
    return outstream.getvalue() # get the contents of the fake file

print(csv_formatter("I have apples, pears, and bananas"))

结果:

"I have apples, pears, and bananas"

此外,一个不错的副作用是将引号考虑在内:更改为:

print(csv_formatter('I have apples, "pears", and bananas'))

您将获得(注意引号中的双引号):

"I have apples, ""pears"", and bananas"

请注意,这正在写入一个具有一列的文件。但是,相同的方法适用于多于1列的列。例如,将写入行替换为:

cw.writerow([string,string,12])

您将获得:

"I have apples, pears, and bananas","I have apples, pears, and bananas",12

现在我想知道为什么您不能将printcsv输出混合,而只共享文件句柄:

with open('test.csv','w', newline='') as out:
    print("Raw Hello", file = out)
    csv.writer(out).writerow('I have apples, pears, and bananas')
    print("Raw Goodbye", file = out)

答案 1 :(得分:0)

只需通过以下方式设置您的字符串即可:

has_ticket