Python 3.1.3 Win 7: csv writerow Error “must be bytes or buffer, not str”

后端 未结 3 1948
野趣味
野趣味 2021-01-14 02:37

Got a simple script which worked perfectly under Python 2.7.1 at my Win xp machine. Now got a win 7 machine with python 3.1.3.

The code is:

owriter.w         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-14 03:12

    In Python 2.X, it was required to open the csvfile with 'b' because the csv module does its own line termination handling.

    In Python 3.X, the csv module still does its own line termination handling, but still needs to know an encoding for Unicode strings. The correct way to open a csv file for writing is:

    outputfile=open("out.csv",'w',encoding='utf8',newline='')
    

    encoding can be whatever you require, but newline='' suppresses text mode newline handling. On Windows, failing to do this will write \r\r\n file line endings instead of the correct \r\n. This is mentioned in the 3.X csv.reader documentation only, but csv.writer requires it as well.

提交回复
热议问题