ziggy ziggy - 1 year ago 144
Python Question

Python write to csv ignore commas

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

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

Answer Source

Strip any comma from each field that you write to the row, eg:

label2 = ''.join(label2.split(','))
facidcsv = ''.join(facidcsv.split(','))
County = ''.join(County.split(','))
row = "{},{},{}\n".format(label2,facidcsv,County)

Generalized to format a row with any number of fields:

def format_row(*fields):
    row = ''
    for field in fields:
        if row:
            row = row + ', ' + ''.join(field.split(','))
            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))


label2 label2, facidcsv, county county
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download