怎么讓這個解決亂碼問題?
from Python生成csv中文亂碼解決辦法
原始代碼:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import csv
#import codecs
with open('test.csv', 'wb') as csvfile:
# csvfile.write(codecs.BOM_UTF8)
spamwriter = csv.writer(csvfile, dialect='excel')
spamwriter.writerow(['測試'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
運行結果:
修改代碼:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import csv
import codecs
with open('test.csv', 'wb') as csvfile:
csvfile.write(codecs.BOM_UTF8)
spamwriter = csv.writer(csvfile, dialect='excel')
spamwriter.writerow(['測試'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
運行結果:
問題解決,只是引入了兩行代碼 :
import codecs
csvfile.write(codecs.BOM_UTF8)