PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 29, 2022

[FIXED] How do I write a comma as a normal text in a CSV file?(the double quote method doesn't work)

 August 29, 2022     csv, python     No comments   

Issue

I'm using Python to output some data in a CSV file. It must absolutely be in a CSV file, I can't use anything else, that's what I'm ordered to do. The comma must be used as a separator, but sometimes the data contains a comma, so I put double quotes around the strings and it put them in one field. That's good so far, however what happens when the data also contains double quotes? There's no limit to what symbol can be contained in the data.


Solution

Don't reinvent the wheel, use the csv module to write out your data:

import csv

with open(outputfilename, 'wb') as outfh:
    writer = csv.writer(outfh)
    writer.writerow(['Data with , commas and nested " quotes', 'works just fine'])

You can adjust quoting behaviour, but the default (Excel compatible) setting will handle quoting of commas and nested quotes for you. Columns containing quotes or commas are quoted, with any embedded quotes doubled.

Demo:

>>> from cStringIO import StringIO
>>> import csv
>>> out = StringIO()
>>> writer = csv.writer(out)
>>> writer.writerow(['Data with , commas and nested " quotes', 'works just fine'])
>>> out.getvalue()
'"Data with , commas and nested "" quotes",works just fine\r\n'


Answered By - Martijn Pieters
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing