Writing a string with comma in one column of CSV file

dn PythonList at DancesWithMice.info
Sat Jan 15 16:11:08 EST 2022


On 16/01/2022 09.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.
> 
> 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?


This is 'CSV' rather than 'Python'. The solution is to "escape" the
string. Ref:
https://stackoverflow.com/questions/769621/dealing-with-commas-in-a-csv-file

-- 
Regards,
=dn


More information about the Python-list mailing list