How can I use quotes without escaping them using CSV?
John Machin
sjmachin at lexicon.net
Wed Apr 9 19:07:54 EDT 2008
On Apr 10, 7:39 am, "Reedick, Andrew" <jr9... at ATT.COM> wrote:
> > -----Original Message-----
> > From: python-list-bounces+jr9445=att.... at python.org [mailto:python-
> > list-bounces+jr9445=att.... at python.org] On Behalf Of jeffself
> > Sent: Wednesday, April 09, 2008 5:11 PM
> > To: python-l... at python.org
> > Subject: How can I use quotes without escaping them using CSV?
>
> > If I put an escape character in, it works. For example, if I use ~ as
> > my escape character, my output looks like this:
> > 0001[tab]Michael L. ~"Mick~" Jones[tab]189
>
> > I don't want that. If I don't include an escape character, it doesn't
> > work.
which means an exception is raised:
_csv.Error: need to escape, but no escapechar set
>
> > Here's my code:
[snip]
> > writer = csv.writer(f, delimiter='\t', quoting=csv.QUOTE_NONE)
[snip]
>
> The documentation is pretty, uhm, obtuse, but you also need to set
> quotechar.
Uhm, "obtuse" applies to angles and people :-) I could agree with
"obscure".
>
> import sys
> import csv
>
> names = ['Michael L. "Mick" Jones', 'Vickie A. Meyers', 'John "Jack"
> Smith']
>
> writer = csv.writer(sys.stdout, delimiter='\t', quotechar='',
> quoting=csv.QUOTE_NONE)
> for i in names:
> writer.writerow(['a', i, 'b'])
>
> output:
> a Michael L. "Mick" Jones b
> a Vickie A. Meyers b
> a John "Jack" Smith b
>
> *****
>
Here's my call:
(1) Code bug: when quoting is set to QUOTE_NONE, it should ignore the
setting of quotechar -- it's irrelevant.
(2) Documentation bug:
"""
quotechar
A one-character string ....
"""
but the code allows setting quotechar to '' and to None. Both work
around the OP's problem; whether they have identical effect in other
situations, I haven't explored.
Cheers,
John
More information about the Python-list
mailing list