Writing a string with comma in one column of CSV file

Mats Wichmann mats at wichmann.us
Sun Jan 16 10:18:29 EST 2022


On 1/15/22 13:56, Mahmood Naderan via Python-list wrote:
> Hi,
> I use the following line to write some information to a CSV file which is comma delimited.
> 
> f = open(output_file, 'w', newline='')
> wr = csv.writer(f)
> ...
> f.write(str(n) + "," + str(key) + "\n" )
> 
> 
> Problem is that key is a string which may contain ',' and this causes the final CSV file to have more than 2 columns, while I want to write the whole key as a single column.

One of the reasons csv is a horrible data interchange format.

If you must... the convention for Excel, which is usually the reason
people are using csv, is you can enclose the entire comma-containing
field in "quote marks" (afaik it must be double-quote).  The convention
for other consumers of csv may or may not accept this - if it's not for
Excel you'll need to check. One gotcha - the opening quote must appear
immediately after the preceding comma separator, you can't pad with
spaces. That is:

"this","should","be","okay, I think"

and not:

"this",  "will",  "not",  "work",  "correctly, I fear"


(the single-word row entries don't have to be in quotes, of course)

If you use the Python csv module it should take care of this - you can
specify the separator sequence and the quote sequence, and it knows to
quote a field correctly if it contains the separator.  Highly recommended.



More information about the Python-list mailing list