Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
748 views
in Technique[技术] by (71.8m points)

csv writer in Python with custom quoting

I'm looking for a way to define custom quoting with csv.writer in Python. There are 4 built-in ways to qoute values:

csv.QUOTE_ALL, csv.QUOTE_MINIMAL, csv.QUOTE_NONNUMERIC, csv.QUOTE_NONE

However I need a quoting mechanism which will emulate Postgres' FORCE QUOTE *, i.e. it will quote all non-None values. With csv.QUOTE_ALL Python will turn None into '' but I would like to have empty string instead.

Is it possible to do that with built-in csv module ( I'm not interested in hacks, I'm already doing that :P )? Or am I forced to write/get some custom csv parser?

And generally: is it possible to write custom quoting mechanism for csv module?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Disable csv quoting and add the quotes yourself:

def quote(col):
    if col is None:
        return ''
    # uses double-quoting style to escape existing quotes
    return '"{}"'.format(str(col).replace('"', '""'))

writer = csv.writer(fileobj, quoting=csv.QUOTE_NONE, escapechar='', quotechar='')

for row in rows:
    writer.writerow(map(quote, row))

By setting both escapechar and quotechar to empty strings you avoid the module quoting your already-quoted values.

The above works as long as you don't use the delimiter in the csv values.

Note that by this time it would just be easier to write comma-delimited lines yourself:

with open(filename, 'w'), fd:
    for row in rows:
        fd.write(','.join(map(quote, row)) + '
')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...