Writing a string with comma in one column of CSV file

alister alister.ware at ntlworld.com
Sat Jan 15 16:00:02 EST 2022


On Sat, 15 Jan 2022 20:56:22 +0000 (UTC), Mahmood Naderan 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?
> 
> 
> Regards,
> Mahmood

you need to quote the data
the easies way to ensure this is to inculde to QUOTE_ALL option when 
opening the file

wr = csv.writer(output, quoting=csv.QUOTE_ALL)



-- 
Chocolate chip.


More information about the Python-list mailing list