Chinaunix
标题:
文件写入转码问题
[打印本页]
作者:
心若寒江雪
时间:
2014-01-23 14:38
标题:
文件写入转码问题
环境:Windows+Sublime Text 2
问题:下面的代码在Sublime上出问题,但是在命令行运行却可以,在Linux也没问题,难道是我的编辑器的问题?
#-*- coding:utf-8 -*-
#uniFile.py -- 将Unicode字符串对象已UTF-8的编码格式写入文件
str=u'大家造起来'
CODE='utf-8'
myfile=open('file','a+')
myfile.write(str.encode(CODE))
myfile.close()
myfile=open('file','r')
f=myfile.read()
myfile.close()
myfile_code=f.decode(CODE)
print myfile_code,
复制代码
报错如下:
Traceback (most recent call last):
File "D:\Python\uniFile.py", line 16, in <module>
print myfile_code,
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-9: ordinal not in range(128)
[Finished in 0.2s with exit code 1]
复制代码
作者:
remyzane
时间:
2014-01-23 14:56
编码和系统有关,mac/linux是utf-8、M$windows是gb2312,还得你自己根据自己系统做测试
转来转去无非就是
encode('utf-8')、 decode('utf-8')、encode('gb2312')、 decode('gb2312')
你自己换来换去试一下,就清楚了。
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2