day17
Serialization
json
Two sets of four methods:
1, dumps (serialization) - loads (deserialization)
dumps (list): convert an object into a string
loads (str): converts a string to an object
- list——str——list
- tuple - str - list (directly into the list, the list of two results are surrounded by [])
- dict——str——dict
- set Nonserializable
lit = [1,22,3,3,45]
print(json.dumps(lit),type(json.dumps(lit)))
str_lst = json.dumps(lit)
lst = json.loads(str_lst)
print(lst,type(lst))
dic = {'username':'宝元'}
# str_dic = json.dumps(dic) # 序列化
str_dic = json.dumps(dic,ensure_ascii=False) # ensure_ascii=False 关闭ascii码
print(str_dic,type(str_dic))
dic1 = json.loads(str_dic) # 反序列化
print(dic1,type(dic1))
2、dump —— load
dump (list, file name): the string to the file object into
load (filename): converts a string file into an object file is read
- list——str——list
- tuple - str - list (directly into the list, the list of two results are surrounded by [])
- dict——str——dict
- set Nonserializable
import json
dic = (1,2,3,4,5)
with open("infoo","a",encoding="utf-8")as f:
json.dump(dic, f)
with open("infoo","r",encoding="utf-8")as f1:
lst1 = json.load(f1)
print(lst1,type(lst1))
# 同时写多个内容 进行序列化
lst = [1,2,3,4,56,]
f = open("info","w",encoding="utf-8")
f.write(json.dumps(lst) + "\n")
f.write(json.dumps(lst) + "\n")
f.write(json.dumps(lst) + "\n")
f.write(json.dumps(lst) + "\n")
f.write(json.dumps(lst) + "\n")
f.close()
# 同时读多个内容进行反序列
f1 = open("info","r",encoding="utf-8")
for i in f1:
l = json.loads(i)
print(l)
f1.close()
pickle
pickle - nb (python convert all objects)
python comes (only python can be used)
Two sets of four methods
1、dumps —— loads
dumps: byte is converted into something similar
loads: turn back
import pickle
lst = [12,3,4,5,768]
t_list = pickle.dumps(lst) # 转换成类似字节
print(t_list)
print(pickle.loads(t_list))
dic = {"user":"郭宝元"}
t_list = pickle.dumps(dic) # 转换成类似字节
print(t_list)
print(pickle.loads(t_list))
import pickle
def func():
print(111)
fun = pickle.dumps(func)
print(fun)
pickle.loads(fun)()
2、dump —— load
dump: converted into something similar bytes written to the file
load: turn back read file
import pickle
dic = {"usern":"baoyuian"}
# dic = {"usern":"宝元"}
pickle.dump(dic,open("info","wb"))
print(pickle.load(open("info","rb")))
import pickle
dic = {"1":2}
f = open("info","wb")
s = "\n".encode("utf-8")
f.write(pickle.dumps(dic)+ s)
f.write(pickle.dumps(dic)+ s)
f.write(pickle.dumps(dic)+ s)
f.close()
f1 = open("info","rb")
for i in f1:
print(pickle.loads(i))
Recommended json
json is common to all languages
pickle (python private)
os module
os module - Python via programmer (interface to interact with the operating system) to the operating system commands
1, the working directory
import os
# print(os.getcwd()) # 查看当前工作路径 ***
# os.chdir("D:\python 笔记\day09") # 路径切换
# print(os.curdir) # 当前(.)
# print(os.pardir) # 父级(..)
2, Folder
import os
os.mkdir("ttt") # 创建一个文件夹 ***
os.rmdir("ttt") # 删除一个文件夹 ***
os.makedirs("ttt/sss/ddd/ee") # 递归创建文件夹 ***
os.removedirs("ttt/sss/ddd/ee") # 递归删除文件夹 ***
print(os.listdir(r"D:\python 笔记\day17")) # 把整个文件夹里面的文件以列表显示 ***
3, file
import os
os.rename("info","infoo") # 重命名文件/目录 ***
os.remove() # 删除一个文件 ***
4, path
import os
# print(os.path.abspath("infoo")) # 通过相对路径获取绝对路径 ***
# print(os.path.split(os.path.abspath("infoo"))) # 将路径以最后一个\切割,结果(路径,文件名)
# print(os.path.dirname(r"D:\python 笔记\day17\__init__.py")) # 获取路径,结果(D:\python 笔记\day17) ***
# print(os.path.exists(r"D:\python 笔记\day17\__init__.py")) # 判断这个路径是否存在 ***
# print(os.path.isdir(r"D:\python 笔记\day17")) # 判断是不是路径 ***
# print(os.path.isfile("__init__.py")) # 判断是不是文件 ***
# print(os.path.isabs("D:\python 笔记\day17\__init__.py")) # 判断是不是绝对路径
# print(os.path.join("D:\\\\","ttt","bbb")) # 路径拼接 ****
# import time
# print(time.time())
# print(os.path.getatime(r"F:\s24\day17\04 序列化.py")) # 最后的修改时间
# print(os.path.getctime(r"F:\s24\day17\04 序列化.py")) # 最后的访问时间
# print(os.path.getmtime(r"F:\s24\day17\04 序列化.py")) # 最后的访问时间
# print(os.path.getsize(r"F:\s24\day09")) # 获取当前文件的大小 ***
sys module
sys-- with python interpreter interactive interface
import sys
# import sys
# if sys.argv[-1] == "alex":
# print("dsb")
# else:
# print("李业dsb")
# print(sys.argv) # *** 当前文件运行,结果:['D:/python 笔记/day17/sys模块.py']
# print(exit(0或1)) # 退出程序,正常退出时exit(0),错误退出sys.exit(1)
# print(sys.path) # 添加自定义模块查找路径 ******
# print(sys.platform) # 区分操作系统然后进行相关逻辑操作 ***
hashlib encryption
Encryption and checksum
md5 algorithm (minimum safety factor), sha1, sha256, sha512
The most commonly used is md5, usually encrypted when using sha1
encryption:
Encrypted content
Encrypted content to be converted into byte
- As long as the same plaintext is the same ciphertext
- As long as the plaintext is not the same ciphertext is not identical
- Not of inverse (can not be decrypted) - md5 Chinese people break
import hashlib
md5 = hashlib.md5()
md5.update("alex123".encode("utf-8"))
print(md5.hexdigest())
md5 = hashlib.md5()
md5.update("alex123".encode("gbk"))
print(md5.hexdigest())
md5 = hashlib.sha1()
md5.update("alex123".encode("utf-8"))
print(md5.hexdigest())
md5 = hashlib.sha256()
md5.update("alex123".encode("utf-8"))
print(md5.hexdigest())
With salt
Fixed salt
import hashlib
md5 = hashlib.md5("常鑫".encode("utf-8"))
md5.update("alex123".encode("utf-8"))
print(md5.hexdigest())
Dynamic salt
user = input("username:")
pwd = input("password:")
import hashlib
md5 = hashlib.md5(user.encode("utf-8"))
md5.update(pwd.encode("utf-8"))
print(md5.hexdigest())
check
ss = "baoyuanalextaibai"
import hashlib
md5 = hashlib.md5()
md5.update(ss.encode("utf-8"))
print(md5.hexdigest())
# 9b674a2402eb25b1ccd2106868bd1ee9
import hashlib # 节省内存
s1 = "baoyuan"
s2 = "alex"
s3 = "taibai"
md5 = hashlib.md5()
md5.update(s1.encode("utf-8"))
md5.update(s2.encode("utf-8"))
md5.update(s3.encode("utf-8"))
print(md5.hexdigest())
# 9b674a2402eb25b1ccd2106868bd1ee9
# f = open(r"F:\s24\day17\python-3.6.6-amd64.exe","rb")
# import hashlib
# md5 = hashlib.md5()
# md5.update(f.read())
# print(md5.hexdigest())
# f = open(r"F:\s24\day17\python-3.6.6-amd64.exe","rb")
# import hashlib
# md5 = hashlib.md5()
# while True:
# msg = f.read(1024)
# if msg:
# md5.update(msg)
# else:
# print(md5.hexdigest())
# break
collections
Counter (): a counter for counting the main *****************
from collections import Counter
# s = [1,1,2,2,3,3]
# s = (1,2,3,3,4,5,6,7,78)
s = "1112233344aaa"
print(dict(Counter(s))) # ***
# 结果是 {'1': 3, '2': 2, '3': 3, '4': 2, 'a': 3}
# 统计元素出现的次数
namedtuple (): Named tuple generation can use the name to access the content of the element tuple
from collections import namedtuple,deque
Point = namedtuple('tu',["a","b","c"]) # 第一个参数是元组的名字,第二参数是元组中元素的[名字,名字]
p = Point({"keu":(1,2,3,4)}, 20,10)
print(p)
# 结果是:tu("a"="keu":(1,2,3,4)},"b"=20,"c"=10)
deque (): deque, from the other side can be quickly and additional objects Release
# lst = deque([1,2,3,4,5,6,7]) # 先进先出
# lst.append(8) # 在最后追加
# lst.appendleft(0) # 在最前加
# lst.pop() # 删除最后的
# lst.popleft() #删除最前的
# print(lst[4]) # 还可以使用索引
OrderedDict (): ordered dictionary
>>> od = OrderedDict()
>>> od['z'] = 1
>>> od['y'] = 2
>>> od['x'] = 3
>>> od.keys() # 按照插入的Key的顺序返回
['z', 'y', 'x']
defaultdict (): Dictionary with default values
# from collections import defaultdict
# dic = defaultdict(list)
# dic["k1"].append(12)
# print(dic)
# li = [11,22,33,44,55,77,88,99,90]
# result = {"key1":[],"key2":[]}
# result = {}
# for row in li:
# if row > 66:
# if 'key1' not in result:
# result['key1'] = []
# result['key1'].append(row)
# else:
# if 'key2' not in result:
# result['key2'] = []
# result['key2'].append(row)
# print(result)
# from collections import defaultdict
# dic = defaultdict(set)
# li = [11,22,33,44,55,77,88,99,90]
# for i in li:
# if i > 66:
# dic["k1"].add(i)
# else:
# dic["k2"].add(i)
# print(dic)