2,何时使用序列化html
dic = {"k1":'v1'}
print(type(dic),dic)
# <class 'dict'> {'k1': 'v1'}
import json
str_d = json.dumps(dic) #序列化
print(type(str_d),str_d)
# <class 'str'> {"k1": "v1"}
#注意,json转换完的字符串类型的字典中的字符串是由""表示的
dic_d = json.loads(str_d) #反序列化
print(type(dic_d),dic_d)
# <class 'dict'> {'k1': 'v1'}
#注意,要用json的loads功能处理的字符串类型的字典中的字符串必须由""表示
#也能够处理嵌套的数据类型
list_dic = [1,['a','b','c'],3,{'k1':'v1','k2':'v2'}]
str_dic = json.dumps(list_dic)
print(type(str_dic),str_dic)
#<class 'str'> [1, ["a", "b", "c"], 3, {"k1": "v1", "k2": "v2"}]
list_dic2 = json.loads(str_dic)
print(type(list_dic2),list_dic2)
#<class 'list'> [1, ['a', 'b', 'c'], 3, {'k1': 'v1', 'k2': 'v2'}]
import json
dic = {1:"a",2:'b'}
f = open('fff','w',encoding='utf-8')
json.dump(dic,f)
f.close()
f = open('fff')
res = json.load(f)
f.close()
print(type(res),res)
import json
dic = {1:"中国",2:'b'}
f = open('F:\临时文件\\fff.txt','w',encoding='utf-8')
json.dump(dic,f,ensure_ascii=False)
f.close()
# 要加入ensure_ascii=False,否则会写入bytes类型
# 也能够不加,不影响load的结果
f = open('F:\临时文件\\fff.txt',encoding='utf-8')
res = json.load(f)
f.close()
print(type(res),res)
5.4,dump load 不能分次往文件里写java
# import json
# dic = {1:"中国",2:'b'}
# f = open('F:\临时文件\\fff.txt','w',encoding='utf-8')
# json.dump(dic,f,ensure_ascii=False)
# json.dump(dic,f,ensure_ascii=False)
# f.close()
# f = open('F:\临时文件\\fff.txt',encoding='utf-8')
# res1 = json.load(f)
# res2 = json.load(f)
# f.close()
# print(type(res1),res1)
# print(type(res2),res2)
5.4,dumps loads 能够实现:分次往文件里写,分次往文件外读python
# json
# dumps {} -- >为了分次写将其写入成一行一行的dumps '{}\n'
# 一行一行的读
l = [{'k':'111'},{'k2':'111'},{'k3':'111'}]
f = open('F:\临时文件\\fff.txt','w')
import json
for dic in l:
str_dic = json.dumps(dic)
f.write(str_dic+'\n')
f.close()
f = open('F:\临时文件\\fff.txt')
import json
l = []
for line in f:
dic = json.loads(line.strip())
l.append(dic)
f.close()
print(l)
<1> Serialize obj to a JSON formatted str.(将obj序列化为json格式的str) <2> Skipkeys:默认值是False,若是dict的keys内的数据不是python的基本类型(str,unicode,int,long,float,bool,None),设置为False时,就会报TypeError的错误。此时设置成True,则会跳过这类key <3> ensure_ascii:当它为True的时候,全部非ASCII码字符显示为\uXXXX序列,只需在dump时将ensure_ascii设置为False便可,此时存入json的中文便可正常显示。 <4> If check_circular is false, then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse). <5> If allow_nan is false, then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity). <6> indent:应该是一个非负的整型,若是是0就是顶格分行显示,若是为空就是一行最紧凑显示,不然会换行且按照indent的数值显示前面的空白分行显示,这样打印出来的json数据也叫pretty-printed json <7> separators:分隔符,其实是(item_separator, dict_separator)的一个元组,默认的就是(‘,’,’:’);这表示dictionary内keys之间用“,”隔开,而KEY和value之间用“:”隔开。 <8> default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. <9> sort_keys:将数据根据keys的值进行排序。 <10> To use a custom JSONEncoder subclass (e.g. one that overrides the .default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.
5.6,json 的格式化输出mysql
import json
data = {'username':['李华','二愣子'],'sex':'male','age':16}
json_dic2 = json.dumps(data,sort_keys=True,indent=2,separators=(',',':'),ensure_ascii=False)
print(json_dic2)
# 结果:
{
"age":16,
"sex":"male",
"username":[
"李华",
"二愣子"
]
}
6,pickle
sql
import pickle
dic = {'k1':'v1','k2':'v2','k3':'v3'}
str_dic = pickle.dumps(dic)
print(str_dic) #一串二进制内容
dic2 = pickle.loads(str_dic)
print(dic2) #字典
import time
struct_time1 = time.localtime(1000000000)
struct_time2 = time.localtime(2000000000)
import pickle
f = open('Fpickle_file','wb')
pickle.dump(struct_time1,f) # dump 第一个
pickle.dump(struct_time2,f) # dump 第二个
f.close()
f = open('pickle_file','rb')
struct_time1 = pickle.load(f) # 加载dump的第一个
struct_time2 = pickle.load(f) # 加载dump的第二个
print(struct_time1.tm_year)
print(struct_time2.tm_year)
f.close()
import shelve
f = shelve.open('shelve_file')
f['key'] = {'int':10, 'float':9.5, 'string':'Sample data'} #直接对文件句柄操做,就能够存入数据
f.close()
import shelve
f1 = shelve.open('shelve_file')
existing = f1['key'] #取出数据的时候也只须要直接用key获取便可,可是若是key不存在会报错
f1.close()
print(existing)
import shelve
#修改不会保存
f1 = shelve.open('shelve_file')
print(f1['key'])
f1['key']['new_value'] = 'this was not here before'
f1.close()
#修改会保存
f2 = shelve.open('shelve_file', writeback=True)
print(f2['key'])
f2['key']['new_value'] = 'this was not here before'
f2.close()
# 文件名:my_module.py
print('from the my_module.py') money=1000
def read1(): print('my_module->read1->money',money) def read2(): print('my_module->read2 calling read1') read1() def change(): global money money=0
import my_modul
# 第一次导入时,执行被导入文件
# 结果:from the my_module.py
import my_module
import my_module
import my_module
# 重复导入,只第一次执行
# 结果:from the my_module.p
import sys
print(sys.modules.keys())
print(sys.path)
总结:首次导入模块my_module时会作三件事:json
1.为源文件(my_module模块)建立新的名称空间,在my_module中定义的函数和方法如果使用到了global时访问的就是这个名称空间。安全
2.在新建立的命名空间中执行模块中包含的代码,见初始导入import my_module网络
3.建立名字my_module来引用该命名空间(即不一样的模块是单独的名称空间,经过 模块名.名称 的方式引用)数据结构
import time as t #将time模块命名为t
print(t.time())
有两中sql模块mysql和oracle,根据用户的输入,选择不一样的sqloracle
#mysql.py
def sqlparse():
print('from mysql sqlparse')
#oracle.py
def sqlparse():
print('from oracle sqlparse')
#test.py
db_type=input('>>: ')
if db_type == 'mysql':
import mysql as db
elif db_type == 'oracle':
import oracle as db
db.sqlparse()
import sys,os,re
from my_module import read1,read2
from demo import read
def read():
print('my read')
read()
10.4,支持 as
from my_module import read1 as read
10.5,支持多行导入
from my_module import (read1,
read2,
money)
if __name__ == '__main__'
pass