Python write to csv ignore commas
<p>I am writing to a csv and it works good, except some of the rows have commas in there names and when I write to the csv those commas throw the fields off...how do I write to a csv and ignore the commas in the rows</p>

<pre><code>header = "Id, FACID, County, \n"
row = "{},{},{}\n".format(label2,facidcsv,County)
with open('example.csv', 'a') as wildcsv:
    if z==0:
        wildcsv.write(header)
        wildcsv.write(row)
    else:
         wildcsv.write(row)
</code></pre>

<p>Strip any comma from each field that you write to the row, eg:</p>

<pre><code>label2 = ''.join(label2.split(','))
facidcsv = ''.join(facidcsv.split(','))
County = ''.join(County.split(','))
row = "{},{},{}\n".format(label2,facidcsv,County)
</code></pre>

<hr>

<p>Generalized to format a row with any number of fields:</p>

<pre><code>def format_row(*fields):
    row = ''
    for field in fields:
        if row:
            row = row + ', ' + ''.join(field.split(','))
        else:
            row = ''.join(field.split(','))
    return row

label2 = 'label2, label2'
facidcsv = 'facidcsv'
county = 'county, county'
print(format_row(label2, facidcsv, county))
wildcsv.write(format_row(label2, facidcsv, county))
</code></pre>

<p><strong>Output</strong></p>

<pre><code>label2 label2, facidcsv, county county
</code></pre>

<hr>

<p>As @TomaszPlaskota and @quapka allude to in the comments, Python's <code>csv</code> <code>writers</code> and <code>readers</code> by default write/read csv fields that contain a delimiter with a surrounding <code>'"'</code>. Most applications that work with csv files follow the same format. So the following is the preferred approach if you want to keep the commas in the output fields:</p>

<pre><code>import csv

label2 = 'label2, label2'
facidcsv = 'facidccv'
county = 'county, county'
with open('out.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerow((label2, facidcsv, county))
</code></pre>

<p><strong>out.csv</strong></p>

<pre><code>"label2, label2",facidccv,"county, county"
</code></pre>

python csv