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. -- https://mail.python.org/mailman/listinfo/python-list