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)
2
  • 2
    You should enclose those in double quotes like it's presented here: stackoverflow.com/a/769675/6313992 - row = "\"{},{},{}\"".format(label2,facidcsv,County) Commented Sep 6, 2016 at 14:17
  • 1
    What about csv module? Commented Sep 6, 2016 at 14:39

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.