Mahmood,
Ask yourself WHY you want to do what you are doing. Are you using the power and 
features of the language or trying to do it step by step in the way that 
earlier languages often made you do it?
Yes, there are ways to include commas in fields of a CSV file and they can lead 
to complications you can completely avoid by NOT using a CSV file. Use 
something where commas are not a field separator and something else that is not 
likely to be in your data (or when found is removed or perhaps replaced with 
something like a space) and can thus be used.
Many files use a TAB or other symbols to delimit data and may be saved with 
names like a .TSV file or others. Python can trivially read in such files often 
simply by telling it to read something like a CSV but specifying the field 
separator is a tab or some other character.
But I have another dumb question. Why are you writing your CSV file by hand and 
a line at a time? I mean there is nothing wrong with that but many people have 
programs where they make an object like a DataFrame and manipulate that to have 
all the data they need and assuming we call the structure df, and they are 
using the pandas module, they can write the entire thing out like this:

df.to_csv('new_file.sv', sep='\t', index=False)

The pandas package fairly easily allows you to load in all the data you need 
rom an external source, search in what you have, make changes or additions, and 
write it out to many kinds of files.
Just a thought. If you like your way, fine, I see another reply suggesting how 
to hide the commas but that can be a problem if humans read and edit the 
results in the external file and do not follow through.

-----Original Message-----
From: Mahmood Naderan via Python-list <python-list@python.org>
To: DL Neil via Python-list <python-list@python.org>
Sent: Sat, Jan 15, 2022 3:56 pm
Subject: Writing a string with comma in one column of CSV file

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.

I know that wr.writerow([key]) writes the entire key in one column, but I would 
like to do the same with write(). Any idea to fix that?


Regards,
Mahmood
-- 
https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to