python2添加编码主要添加下面三行

1
2
3
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

直接上完整测试代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import datetime
import os

data = ((1, u'1111', u'2222', u'\u7f16\u7801\u6d4b\u8bd5',
u'123', u'dafdsfs', u'adsfd', u'fdasf', u'fdsaf',
u'', u'', u'', datetime.date(3021, 3, 2), u'Unknown'), (
2, u'222', u'23323233', u'\u7f16\u7801\u6d4b\u8bd5\u54c8\u54c8',
u'333', u'ccc', u'fadsf', u'dfdfdf', u'sddsdsd', u'', u'', u'', datetime.date(4021, 3, 2),
u'\u7f16\u7801\u6d4b\u8bd5\u54c8\u54c8'))

filepath = 'test2.csv'
if os.path.exists(filepath):
os.remove(filepath)
for i in data:
for c in i:
with open(filepath,'a') as f:
f.write(str(c))
f.write(',')
with open(filepath, 'a') as f:
f.write('\n')

效果如下:
效果