代码之家  ›  专栏  ›  技术社区  ›  max

为csv编写安全的字符串?

  •  0
  • max  · 技术社区  · 6 年前

    我需要使用print语句写出一个csv文件,所以我不能使用csv writer库。但是,如预期的那样,逗号将字符串分成不同的列。如何在写入前转换字符串来转义逗号?

    例如:

    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 回复  |  直到 6 年前
        1
  •  4
  •   Jean-François Fabre    6 年前

    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"
    

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

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

    print

    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)
    
        2
  •  0
  •   Lev Zakharov Riss    6 年前

    my_str = '"I have apples, pears, and bannanas"'