6

I'm trying to export a list of strings to csv using comma as a separator. Each of the fields may contain a comma. What I obtain after writing to a csv file is that every comma is treated as a separator.

My question is: is it possible to ignore the commas (as separators) in each field?

Here is what I'm trying, as an example.

import csv

outFile = "output.csv"
f = open(outFile, "w")

row = ['hello, world' , '43333' , '44141']

with open(outFile, 'w') as writeFile:
    writer = csv.writer(writeFile)
    writer.writerow(row)

writeFile.close()

The output looks like this: outputObtained

What I would like is something like this: outputExpected

I think a way to solve this would be to use a different separator, as I read in some sites. But my question is if there is a way to solve this using comma (',') separators.

Thanks

10
  • "is if there is a way to solve this using comma (',') separators" I highly doubt that. How would the parsing software know what comma is which? Commented Jan 25, 2019 at 16:35
  • are there any pattern which you need? like the first comma that encounters in a row etc.. Commented Jan 25, 2019 at 16:41
  • @DeepSpace: the de facto standard is to allow commas in values enclosed by double quotes. Commented Jan 25, 2019 at 16:42
  • 3
    csv is correctly putting quotes around "hello, world" to preserve the embedded comma. The problem is with the process that reads the csv file to produce the spreadsheet in the image, which you haven't shown us. Commented Jan 25, 2019 at 16:43
  • 3
    You just need to tell Calc/Excel that your quoting character is a " Commented Jan 25, 2019 at 16:44

3 Answers 3

1

You just need to tell Calc/Excel that your quoting character is a "

Sign up to request clarification or add additional context in comments.

Comments

0

You can do .replace(',','') which will replace the commas in the text with a space (or whatever else you want.

I don't know a way to keep the comma in the text but not let it act as a separator, like \, maybe? Somebody else could probably shed some light on that.

Comments

0

I believe you can try wrapping the fields which contain a non-delimiting comma in double quotes. If that does not work, you are probably out of options. Afterall, you need to somehow convey the information about which comma is doing what to the software that is doing the CSV display for you or the user.

Perhaps this will be helpful:

https://www.rfc-editor.org/rfc/rfc4180#page-3

  1. Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes. For example:

    "aaa","b CRLF bb","ccc" CRLF zzz,yyy,xxx

Comments

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.