网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

pythonBinarytoStr编码格式化问题

相信编码问题困扰了不少coder,最近遇到的一些坑分享给大家。

文圣网站制作公司哪家好,找创新互联!从网页设计、网站建设、微信开发、APP开发、成都响应式网站建设公司等网站项目制作,到程序开发,运营维护。创新互联自2013年创立以来到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联

1、通用方法 :decode对应的编码

>>> b"abcde"
b'abcde'

# utf-8 is used here because it is a very common encoding, but you
# need to use the encoding your data is actually in.
>>> b"abcde".decode("utf-8") 
'abcde'

2、正反编码:encode完了decode

import urllib.request#urlurl="http://www.baidu.com/"#请求request = urllib.request.Request(url)#爬取结果response = urllib.request.urlopen(request)
s = response.read()
s=s.decode('utf-8')
s=s.encode('gbk','ignore').decode('gbk');
print(s)
input('...')

3、文件流的方式

针对文件的存储,如图片、音乐,需要以文件为载体作为读写

def read_file(filename):
    with open(filename, 'rb') as f:
        photo = f.read()
    return photo

4、Binary/LargeBinary/BLOB 字节流类读写

这个时候就要用到我们的终极武器,pickle模块。以上的方法针对特殊字符的字符串格式的读取是invalid byte。

insert = self.jobs_t.insert().values(**{
    'id': job.id,
    'next_run_time': datetime_to_utc_timestamp(job.next_run_time),
    'job_state': pickle.dumps(job.__getstate__(), self.pickle_protocol)  # write
})

res[APSchedulerJob.id] = {'next_run_time': APSchedulerJob.next_run_time, 'job_state': str(pickle.loads(APSchedulerJob.job_state)), }  # read

结果:
{
  "dbintobalant": {
    "job_state": "{'version': 1, 'id': 'dbintobalant', 'func': 'app.main.views:db_balant', 'trigger': , 'executor': 'default', 'args': (), 'kwargs': {}, 'name': 'dbintobalant', 'misfire_grace_time': 1, 'coalesce': False, 'max_instances': 5, 'next_run_time': datetime.datetime(2018, 6, 22, 14, 8, tzinfo=)}", 
    "next_run_time": 1529647680.0
  }, 
  "hwintobalant": {
    "job_state": "{'version': 1, 'id': 'hwintobalant', 'func': 'app.main.views:hw_balant', 'trigger': , 'executor': 'default', 'args': (), 'kwargs': {}, 'name': 'hwintobalant', 'misfire_grace_time': 1, 'coalesce': False, 'max_instances': 5, 'next_run_time': datetime.datetime(2018, 6, 22, 14, 9, tzinfo=)}", 
    "next_run_time": 1529647740.0
  }, 
  "mwintobalant": {
    "job_state": "{'version': 1, 'id': 'mwintobalant', 'func': 'app.main.views:mw_balant', 'trigger': , 'executor': 'default', 'args': (), 'kwargs': {}, 'name': 'mwintobalant', 'misfire_grace_time': 1, 'coalesce': False, 'max_instances': 5, 'next_run_time': datetime.datetime(2018, 6, 22, 14, 8, tzinfo=)}", 
    "next_run_time": 1529647680.0
  }
}

如有其他好的方法,欢迎交流。


当前题目:pythonBinarytoStr编码格式化问题
当前地址:http://bjjierui.cn/article/jigggp.html

其他资讯