How can I use quotes without escaping them using CSV?

jeffself jeff.self at gmail.com
Wed Apr 9 17:10:44 EDT 2008


I'm reading data out of an Excel spreadsheet using the XLRD module.
The spreadsheet contains a list of election results.  The fields are
as follows: Precinct, Candidate, Votes

The problem is candidate names can be funky, for instance:  Michael L.
"Mick" Jones

I cannot for the life of me figure out how to get the CSV module to
allow a name like this to be written to a file.  Why does it insist on
an escape character when I'm telling it that the delimiter should be
'\t'?  I want the quotes to go to the file and I want the tab-
delimited file to look like this:

0001[tab]Michael L. "Mick" Jones[tab]189
0002[tab]Vickie A. Meyers[tab]221
0003[tab]John "Jack" Smith[tab]187

Note: I don't want [tab] to display, I want a real tab there.

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.


Here's my code:
import sys
import csv
from readexcel import *

f = open("results.txt", 'wb')
book = sys.argv[1]
sheet = sys.argv[2]

xl = readexcel(book)
sheetnames = xl.worksheets()

for s in sheetnames:
    if s == sheet:
        writer = csv.writer(f, delimiter='\t', quoting=csv.QUOTE_NONE)
        for row in xl.getiter(s):
 
writer.writerow((row['Precinct'],row['Candidate'],unicode(int(row['Votes']))))
f.close()


Thanks!



More information about the Python-list mailing list