如何在python中写入csv时转义分号 [英] how to escape semicolons when writing to csv in python

查看:298
本文介绍了如何在python中写入csv时转义分号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有一个列表列表,表示要在csv文件中写入的数据。我的代码是:

 对于zip中的n,d,p(名称,日期,帖子):
writer.writerow([i,n,d,p])

但是,其中的某些字符串帖子包含分号,这将在csv中创建新的单元格。我在网上查看并尝试


  1. 设置引号= csv.QUOTE_ALL

  2. 包装每个帖子字符串内双引号

  3. 使用普通的python而不是csv.writer

  4. 来包装双引号内的分号
  5. ol>

    到目前为止没有任何工作。任何帮助,我发现的每个在线转义逗号答案都涉及(1)或(2),这对我不起作用。



    编辑:这是我的意思的示例



    当我写行['a ','b','c','d; e'],d和e放入不同的单元格中,例如:

      a | b | c | d | e 

    与我想要的相对,即:

      a | b | c | d; e 


    解决方案

    我建议使用熊猫来转换数据

     >>转换为CSV文件,因为它更加容易,而且您无需关心字符的处理。 arr = [{ a:1, b:2, c:3},{ a:2, b:3, c:4}] 
    >> ;> dataFrame = pd.DataFrame(arr)
    >> dataFrame
    a b c
    0 1 2 3
    1 2 3 4
    > dataFrame.to_csv( test.csv,index = 0)


    I have a list of lists in python that represents data to be written in a csv file. My code for that is :

    for n, d, p in zip(names, dates, posts):
            writer.writerow([i, n, d, p])
    

    However, some of the strings in posts contain semicolons, and this creates new cells in the csv. I've looked online and tried

    1. setting quoting=csv.QUOTE_ALL
    2. wrapping each post string inside double quotes
    3. wrapping the semicolons inside double quotes
    4. using normal python write instead of csv.writer

    Nothing's worked so far. Any help, every online answer to escaping comma's I've found involves (1) or (2) which doesn't work for me. Please help!

    Edit: Here's an example of what I mean

    When I write the row ['a', 'b', 'c', 'd;e'], the d and e get put into different cells, like:

    a | b | c | d | e
    

    As opposed to what I want, which is:

    a | b | c | d;e
    

    解决方案

    I will recommend using pandas for converting data into CSV as it's much easier and you don't need to care about handling characters.

    >>> arr = [{"a":1,"b":2,"c":3},{"a":2,"b":3,"c":4}]
    >>> dataFrame = pd.DataFrame(arr)
    >>> dataFrame
       a  b  c
    0  1  2  3
    1  2  3  4
    >>> dataFrame.to_csv("test.csv",index = 0)
    

    这篇关于如何在python中写入csv时转义分号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆