portable way to write csv file in python 2 or python 3

后端 未结 2 1835
故里飘歌
故里飘歌 2020-11-27 07:57

On my Windows box, I usually did this in python 2 to write a csv file:

import csv
f = open(\"out.csv\",\"wb\")
cr = csv.writer(f,delimiter=\';\')
cr.writerow         


        
2条回答
  •  佛祖请我去吃肉
    2020-11-27 08:45

    On Windows, I found a python 2 & 3 compliant way of doing it changing csv lineterminator option (which defaults to "\r\n" which makes one \r too many when file is open in text mode in Windows)

    import csv
    
    with open("out.csv","w") as f:
        cr = csv.writer(f,delimiter=";",lineterminator="\n")
        cr.writerow(["a","b","c"])
        cr.writerow(["d","e","f"])
        cr.writerow(["a","b","c"])
        cr.writerow(["d","e","f"])
    

    Whatever the python version, that will create a csv file without the infamous "blank lines".

    The only drawback is that on Linux, this method would produce \r-free files, which is maybe not the standard (although files still opens properly in excel, no blank lines and still several lines :))

    the problem persists on 3.6.2 (Just checked myself like I should have some time ago)

提交回复
热议问题