简体   繁体   中英

How to fix a default new line delimiter in a cx_Oracle csv output into a semicolon delimiter format?

Here is an extract of the script I'm using. It's basically extracting data from an Oracle database, and then writes it in a .csv file.

All is working well, except the csv writing: the final csv didn't fit to the classical csv format: it was new line delimited and I fixed it.

But now I can't get the simple quote characters even though I'm supposedly using the right csv.register_dialect code.

Below are the code and the examples:

    FILE=open(files,'wb')
    csv.register_dialect('test_dialect', delimiter=';', escapechar= '\\', quotechar = '\'', doublequote=False)
    output=csv.writer(FILE, 'test_dialect')

Here is what I get in test.csv:

    INSEE_COMM
    01012
    01014
    01031

Here is what I want to get in test.csv:

    INSEE_COMM
    '01012'
    '01014'
    '01031'

I edited my code and got rid of the extra lines with the "wb" parameter. But I didn't get the quote characters around INSEE_COM values

Could you give me a hint, some keywords or some help?

So you want an extra trailing semicolon on each line? Just change your CSV dialect to this...

csv.register_dialect('dial_test', 
    delimiter=';', 
    lineterminator=';\n', 
    quoting=csv.QUOTE_NONE, 
    escapechar='\\', 
    doublequote=False)

Ok, I went through these simple problems and finally found solutions:

The first problem was the extra lines in the csv. I solved it there:

    FILE=open(filename,'wb')

The 'wb' is for 'write binary': it solves issues in .exe, image files (like end of line) that the 'w' parameter alone doesn't.

I requested a final semicolon for each line in my csv: it was useless. A classical semicolon delimited csv has no semicolon at the end of the line.

And for the simple quotes, you just need to add quoting=csv.QUOTE_ALL in your dialect definition:

    csv.register_dialect('dial_quote', delimiter=';', escapechar= '\\', quotechar = '\'',quoting=csv.QUOTE_ALL, doublequote=False)

QUOTE_NONE would be as efficient on the opposite.

There you are!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM