资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

pythonBinarytoStr编码格式化问题-创新互联

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

创新互联公司是一家从事企业网站建设、成都做网站、网站设计、行业门户网站建设、网页设计制作的专业网络公司,拥有经验丰富的网站建设工程师和网页设计人员,具备各种规模与类型网站建设的实力,在网站建设领域树立了自己独特的设计风格。自公司成立以来曾独立设计制作的站点1000多家。

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
  }
}

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

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


新闻标题:pythonBinarytoStr编码格式化问题-创新互联
网站URL:http://cdkjz.cn/article/djedgd.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220