python3 字符编码及JSON格式总结
- 首先是字符编码格式问题
在python3中常见编码有,UTF-8
,ASCII
,Unicode
,UTF-8
是可变长编码,ASCII
是英文编码,Unicode
可以容纳所有语言的编码
在计算机内存中,统一使用Unicode
编码,当需要保存到硬盘或者传输的时候就转换成UTF-8
编码
encode()
方法,encode在英语中的意思是编码,编制成计算机语言
,所以encode()
就是把Unicode
格式的str转换成编码二进制码表示出来
decode()
方法,我们从网络或磁盘上读到的是bytes
类型的,需要用decode()
方法解码成人类能够读懂的语言 然后是文件的
write
,read
,open
,注意其中的open()
可以指明参数encoding=xxxx
open()
函数的用法 ,函数原型:open(file[, mode[, buffering[, encoding[, errors[, newline[, closefd=True]]]]]])
最后要重点讲下JSON文件的读写问题(做一个项目的时候很迷糊)
- 导入json库,其中有
json.dumps()
,json.loads()
这两个函数是用于处理字符串和JSON格式的数据的关系,json.dump()
,json.load()
是用来处理文件和JSON格式之间的关系,并且要注意json.dumps()
和json.dump()
默认是使用ASCII
码进行编码的,要想获得中文要指定ensure_ascii=False
,注意! - json.dumps()
将python数据结构转换JSON
- 导入json库,其中有
import json
data = {
'name' : 'ACME',
'shares' : 100,
'price' : 542.23
}
json_str = json.dumps(data)
- json.loads()
将JSON转化为python数据结构
data = json.loads(json_str)
- json.dump()
将python数据结构以JSON格式写入文件
with open('data.json', 'w') as f:
json.dump(data, f)
- json.load()
将JSON格式的文件以python数据结构读出来
with open('data.json', 'r') as f:
data = json.load(f)