2,什么时候使用序列化
dic = {"k1":‘v1‘}
print(type(dic),dic)
import json
str_d = json.dumps(dic) #序列化 #>>>
print(type(str_d),str_d)
dic_d = json.loads(str_d) #反序列化 #>>>
print(type(dic_d),dic_d)
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(‘fff‘,‘w‘,encoding=‘utf-8‘)
json.dump(dic,f,ensure_ascii=False) #要加入ensure_ascii=False,不然会写入bytes类型
f.close()
f = open(‘fff‘,encoding=‘utf-8‘)
res = json.load(f)
f.close()
print(type(res),res)
5.4(好像不能这样写)
# import json
# json dump load
# dic = {1:"中国",2:‘b‘}
# f = open(‘fff‘,‘w‘,encoding=‘utf-8‘)
# json.dump(dic,f,ensure_ascii=False)
# json.dump(dic,f,ensure_ascii=False)
# f.close()
# f = open(‘fff‘,encoding=‘utf-8‘)
# res1 = json.load(f)
# res2 = json.load(f)
# f.close()
# print(type(res1),res1)
# print(type(res2),res2)
5.4,分次往里写,分次往外读
# json
# dumps {} -- >为了分次写将其写入成一行一行的dumps ‘{}\n‘
# 一行一行的读
# ‘{}\n‘
# ‘{}‘ loads
l = [{‘k‘:‘111‘},{‘k2‘:‘111‘},{‘k3‘:‘111‘}]
f = open(‘file‘,‘w‘)
import json
for dic in l:
str_dic = json.dumps(dic)
f.write(str_dic+‘\n‘)
f.close()
f = open(‘file‘)
import json
l = []
for line in f:
dic = json.loads(line.strip())
l.append(dic)
f.close()
print(l)
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)
f = open(‘pickle_file‘,‘wb‘)
pickle.dump(struct_time1,f)
pickle.dump(struct_time2,f)
f.close()
f = open(‘pickle_file‘,‘rb‘)
struct_time1 = pickle.load(f)
struct_time2 = pickle.load(f)
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()
import demo
def read():
print(‘my read func‘)
demo.read()
print(demo.money)
import sys
print(sys.modules.keys())
print(sys.path)
import time as t #将time模块命名为t
print(t.time())
oracle
mysql
if 数据库 == ‘oracle’:
import oracle as db
elif 数据库 == ‘mysql’:
import mysql as db
#两个数据图库都有 connect方法
#就都可以用 db.connect 调用
#想要操作数据库就要:
# 连接数据库 db.connect
# 登录认证
# 增删改查
# 关闭数据库
from time import sleep
from demo import read
def read():
print(‘my read‘)
read()
if __name__ == ‘__main__‘
pass
原文:https://www.cnblogs.com/eternity-twinkle/p/10538923.html