Issue with UTF-/ encoding on csv file for excel

前端 未结 3 1943
傲寒
傲寒 2020-12-17 04:39

EDIT:

As suggested special chars are displayed correctly if I use notepad++ to open the csv file. They are displayed correctly too when I import the csv file into

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-17 05:01

    I fixed this issue using UTF-8 BOM encoding.

    # -*- coding: utf-8-sig-*-
    import unicodecsv as csv
    import codecs
    import sys
    reload(sys)
    sys.setdefaultencoding("utf-8-sig")
    def write_csv(file,headers):
    
    
        resultFile =codecs.open(file, "w+", "utf-8-sig")
    
        #headers=[s.encode('utf-8') for s in headers]
        wr = csv.writer(resultFile, dialect='excel',delimiter=";",encoding="utf-8-sig")
        wr.writerow(headers)
    
        resultFile.close()
    
    headers=[""]
    headers.append("Command")
    headers.append("Vérification")
    write_csv(r"C:\Users\ATHENA-HDA\AppData\Local\Temp\test2.txt",headers)
    

提交回复
热议问题