分类 "Python" 下的文章

问题:python3,写文件时出现错误TypeError: must be str, not bytes
解决:让写文件时支持binary模式
方法:
outFile = open(final_path, 'wb')
output_file.write(file_data['body'])
output_file.close()

错误情况:UnicodeEncodeError: 'ascii' codec can't encode characters in position······

指定一个字条串为unicode编码

str = u'你好,hello'

判断字条串是否为unicode

isinstance(str, unicode)
字符串str为unicode码时
str.encode('utf-8')    #这样就可以转换成utf-8编码了
要进行编码转换,都需要先用decode方法将其转换成unicode编码,再使用encode方法将其转换成其他编码。
注:http://www.jb51.net/article/17560.htm
注:这是python2.7,在python3中不适用

问题:从cookie中获取的数据是bytes类型,希望转换成str类型
解决:使用decode
方法:
一、将str类型转换成bytes类型
a='abc需要'                                       此时a为str类型,打印出a='abc需要'
b = a.encode('utf-8')                        按utf-8方式编码
b'abcxe9x9cx80xe8xa6x81'      打印出来的b为bytes类型
二、将bytes类型转换成str
c = b.decode()
三、在python2.7中
a='abc需要'                                        此时a为str类型,打印出的a =  'abcxe9x9cx80xe8xa6x81'
b=a.decode('utf-8')                           此时b为unicode,打印出的b = u'abcu9700u8981'

错误:TypeError: datetime.datetime(2015, 12, 16, 7, 19, 34) is not JSON serializable
解决:Python自带的json序列化工具不能序列化datetime类型的数据
方法:
一、将获得的数据列表化
bookList = self.db.query(BookList.id,BookList.name,BookList.published).order_by('published desc').offset(0).limit(10).all()
bookList = [list(b) for b in bookList]
二、对datetime数据格式化
for b in bookLIst:
b[1] = b[1].strftime('%Y-%m-%d %H:%M:%S')
三、完成上面就可以进行json操作了
self.write({'bookLIst':booklist})

问题:用putty连接虚拟机,运行pygame程序后,无法显示,直接乱码,创建窗口失败
方法:原因是没有X Server,可以在windows下安装Xming程序,同时更改putty的连接设置,之后再运行你开发的pygame程序就可以了。
同时不安装Xming的话,python GUI库tkinter也无法使用,会报错,如下:
_tkinter.TclError: couldn't connect to display "localhost:10.0"
注:配置信息参考http://www.2cto.com/os/201407/315646.html