How to write a csv file in binary mode?

后端 未结 1 787
情歌与酒
情歌与酒 2020-12-12 03:36

Does python\'s csv writer not support binary mode anymore?

I haven\'t had to write in \'b\' mode until now and i\'m getting very annoying errors like so:

<         


        
相关标签:
1条回答
  • 2020-12-12 03:57

    The csv module in Python 3 always attempts to write strings, not bytes:

    To make it as easy as possible to interface with modules which implement the DB API, the value None is written as the empty string. [...] All other non-string data are stringified with str() before being written.

    That means you have to pass it a file object that accepts strings, which usually means opening it in text mode.

    If you are stuck with a file object that wants bytes, wrap it in an io.TextIOWrapper to handle str->bytes encoding:

    # assuming you want utf-8
    with io.TextIOWrapper(binary_file, encoding='utf-8', newline='') as text_file:
        w = csv.writer(text_file)
    
    0 讨论(0)
提交回复
热议问题