3

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:
        wildcsv.write(header)
        wildcsv.write(row)
    else:
         wildcsv.write(row)
ziggy
  • 1,488
  • 5
  • 23
  • 51
  • 2
    You should enclose those in double quotes like it's presented here: http://stackoverflow.com/a/769675/6313992 - `row = "\"{},{},{}\"".format(label2,facidcsv,County)` – Tomasz Plaskota Sep 06 '16 at 14:17
  • 1
    What about [csv](https://docs.python.org/2/library/csv.html#csv.writer) module? – quapka Sep 06 '16 at 14:39

1 Answers1

5

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(','))
        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))

Output

label2 label2, facidcsv, county county

As @TomaszPlaskota and @quapka allude to in the comments, Python's csv writers and readers by default write/read csv fields that contain a delimiter with a surrounding '"'. 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:

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))

out.csv

"label2, label2",facidccv,"county, county"
Craig Burgler
  • 1,749
  • 10
  • 19
  • hmm okay this could work--I have about 20 something fields to write tho (didnt include that in the question) any way to do a mass comma remove on all columns and rows? – ziggy Sep 06 '16 at 14:19