python Binary to Str 编码格式化问题
admin
2023-07-25 01:22:11
0

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

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

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

相关内容

热门资讯

美国查封近400个盗播世界杯赛... 美国司法部官员26日说,美国查封了近400个非法直播世界杯赛事的互联网域名。 美国司法部说,被查封的...
原创 欧... 文/王新喜 在这个被热浪炙烤的夏天,中国空调在欧洲被抢疯,欧洲人的夏天被拯救了。 以法国为例,如今法...
市场监管总局给AI立规矩 智能... 央广网北京6月26日消息(记者胡波 陈爱海)据中央广播电视总台经济之声报道,随着大模型技术迭代升级,...
原创 美... 看起来您提供的内容主要是一些乱码、符号和零散的年份数字,没有完整的语义或连续的句子可供改写。我可以帮...
高雄选战诡异僵局:蓝绿全员摆铁... 台湾年底将举行县市长选举,绿营长期执政的高雄受外界关注,但选情相当冷,蓝绿阵营都低调、谨慎、怕犯错、...
悬赏公告背后的“老赖”:被指隐... 澎湃新闻记者 朱远祥截至6月27日,中国执行信息公开网公布的失信被执行人已超863万个,这个数字还在...
以用户体验为中心的5G-A网络... [中国,上海,2026年6月26日] 在2026 MWC上海期间,华为成功举办5G-A产业演进峰会。...
电脑涨价潮来了!有电脑内存条2... 苹果公司最近宣布,上调全球多个市场部分笔记本电脑和平板电脑售价,涨幅在16%至25%不等。国内市场多...
马克龙回应法国极端高温:不能用... 据凤凰卫视报道,针对多日来法国遭遇的极端热浪,法国总统马克龙6月26日表示,法国在气候变化适应方面已...
一开空调就跳闸的原因 空调跳闸是一个让人感到困惑和烦恼的问题,尤其是在炎热的夏季。这种情况通常是由以下原因导致的:1. 电...