how to escape semicolons when writing to csv in python

…衆ロ難τιáo~ 提交于 2020-01-04 10:58:32

问题


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

回答1:


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)



回答2:


You can use tab as a delimiter.

You can write the file and open later using pandas or csv, setting delimiter as “\t”.

It works for opening in Excel or similar programs too.

Example using csv for writing:

import csv

with open(<filename>, "w") as file:
    writer = csv.writer(file, delimiter="\t")

Example using csv for reading:

import csv

with open(<filename>, "r") as file:
    reader = csv.reader(file, delimiter="\t")



回答3:


It could be an issue with whatever program you're viewing the CSV with. I had the same problem and it was because I had a checkbox selected in my spreadsheet software to delimit by both commas and semicolons.



来源:https://stackoverflow.com/questions/49788330/how-to-escape-semicolons-when-writing-to-csv-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!