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