how to escape semicolons when writing to csv in py

2019-07-18 08:11发布

问题:

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")