复习
'''
项目开发规范
ATM
-- bin: 可执行文件
# run.py
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # ATM文件夹
sys.path.append(BASE_DIR)
from core import main
-- core:核心代码
# main.py
from setting import settings
from lib import mp
# login.py
# from bin.run import BASE_DIR
# u_info = os.path.join(BASE_DIR, 'db', 'user.info')
from setting.settings import USER_INFO
# register.py
# from bin.run import BASE_DIR
# u_info = os.path.join(BASE_DIR, 'db', 'user.info')
from setting.settings import USER_INFO
-- db:数据库
# user.info
-- setting:配置
# settings.py
from bin.run import BASE_DIR
USER_INFO = os.path.join(BASE_DIR, 'db', 'user.info')
-- lib:公用模块
# mp文件夹
__init__.py
m1.py
m2.py
-- log:日志
-- static:静态资源
-- interface:接口
# user.info
-- setting:配置
# settings.py
from bin.run import BASE_DIR
USER_INFO = os.path.join(BASE_DIR, 'db', 'user.info')
-- lib:公用模块
# mp文件夹
__init__.py
m1.py
m2.py
-- log:日志
-- static:静态资源
-- interface:接口
2.时间: time calendar datetime
3.系统 sys, os, os.path
4.sys.argv:结束文件作为脚本执行传入的参数
cmd:python3 py脚本 参数们
'''
```
cmd:python3 py脚本 参数们
'''
```
作业
# 递归遍历
def list_file(folder, suffix, ls=[]):
if not os.path.exists(folder):
return ls
if os.path.isfile(folder):
if folder.endswith(suffix):
ls.append(folder)
return ls
for file in os.listdir(folder):
file_path = os.path.join(folder, file)
list_file(file_path, suffix)
return ls
folder = r'F:\python8期\课堂内容\day18\代码'
suffix = 'py'
ls = list_file(folder, suffix)
print(ls)
```
suffix = 'py'
ls = list_file(folder, suffix)
print(ls)
```
# 递归删除
def delete_folder(folder):
if not os.path.exists(folder):
return False
if os.path.isfile(folder):
os.remove(folder)
return True
for file in os.listdir(folder):
file_path = os.path.join(folder, file)
if os.path.isfile(file_path):
os.remove(file_path) # 子文件删空了
else:
delete_folder(file_path) # 子文件夹删空了
os.rmdir(folder) # 可以删除当前文件夹了
def delete_folder(folder):
if not os.path.exists(folder):
return False
if os.path.isfile(folder):
os.remove(folder)
return True
for file in os.listdir(folder):
file_path = os.path.join(folder, file)
if os.path.isfile(file_path):
os.remove(file_path) # 子文件删空了
else:
delete_folder(file_path) # 子文件夹删空了
os.rmdir(folder) # 可以删除当前文件夹了
folder = r'F:\python8期\课堂内容\day19\代码\tt'
delete_folder(folder)
```
delete_folder(folder)
```
# 验证码
def random_code0(num):
code = ""
for i in range(num):
d = random.randint(65, 90)
x = random.randint(97, 122)
n = random.randint(0, 9)
code += random.choice([chr(d), chr(x), str(n)])
return code
code = ""
for i in range(num):
d = random.randint(65, 90)
x = random.randint(97, 122)
n = random.randint(0, 9)
code += random.choice([chr(d), chr(x), str(n)])
return code
def random_code1(num):
code = ""
for i in range(num):
choose = random.randint(1, 3)
if choose == 1:
c = chr(random.randint(65, 90))
elif choose == 2:
c = chr(random.randint(97, 122))
else:
c = str(random.randint(0, 9))
code += c
return code
code = ""
for i in range(num):
choose = random.randint(1, 3)
if choose == 1:
c = chr(random.randint(65, 90))
elif choose == 2:
c = chr(random.randint(97, 122))
else:
c = str(random.randint(0, 9))
code += c
return code
def random_code2(num):
target = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'
code_list = random.sample(target, num)
return ''.join(code_list)
target = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'
code_list = random.sample(target, num)
return ''.join(code_list)
r1 = random_code2(18)
print(r1)
print(r1)
```
## random:随机数
'''
(0, 1):random.random()
[1, 10]:random.randint(1, 10)
[1, 10):random.randrange(1, 10)
(1, 10):random.uniform(1, 10)
单例集合随机选择1个:random.choice(item)
单例集合随机选择n个:random.sample(item, n)
洗牌单列集合:random.shuffle(item)
一。json
# json语言,就是一种有语法规范的字符串,用来存放数据的,完成各种语言之间的数据交互
# 1.就是{}与[]的组合,{}存放双列信息(类比为字典),[]存放单列信息(类比为列表)
# 2.{}的key必须是字符串,且必须用""包裹
# 3.{}与[]中支持的值的类型: dict | list | int | float | bool | null | str
# 序列化:将对象转换为字符串
# dumps:将对象直接序列化成字符串
# dump:将对象序列化成字符串存储到文件中
obj = {'name': 'Owen', "age": 18, 'height': 180, "gender": "男"}
r1 = json.dumps(obj, ensure_ascii=False) # 取消默认ascii编码,同该文件的编码 utf-8 py3默认,py2规定文件头
print(r1)
with open('1.txt', 'w', encoding='utf-8') as wf:
json.dump(obj, wf, ensure_ascii=False)
json.dump(obj, wf, ensure_ascii=False)
# 反序列化:将字符串转换为对象
json_str = '{"name": "Owen", "age": 18, "height": 180, "gender": "男"}'
r2 = json.loads(json_str, encoding='utf-8') # 默认跟当前文件被解释器执行的编码走
print(r2, type(r2))
with open('1.txt', 'r', encoding='utf-8') as rf:
r3 = json.load(rf)
print(r3, type(r3))
```
r3 = json.load(rf)
print(r3, type(r3))
```
二。pickle
# 为什么有很多序列化和反序列化模块
# 因为程序中会出现各种各样的对象,如果要将这些对象持久化存储,必须先序列化
# 只有序列化存储后,必须有对应的反序列化,才能保证存储的数据能被重新读取使用
# 什么是序列化:对象 => 字符串
# 为什么序列化:存 或 传
# 为什么要反序列化:再次使用
# 为什么有很多序列化模块:存与取的算法可以多种多样,且要配套
# 为什么序列化:存 或 传
# 为什么要反序列化:再次使用
# 为什么有很多序列化模块:存与取的算法可以多种多样,且要配套
import pickle
obj = {"name": 'Owen', "age": 18, "height": 180, "gender": "男"}
# 序列化
r1 = pickle.dumps(obj)
print(r1)
with open('2.txt', 'wb') as wf:
pickle.dump(obj, wf)
obj = {"name": 'Owen', "age": 18, "height": 180, "gender": "男"}
# 序列化
r1 = pickle.dumps(obj)
print(r1)
with open('2.txt', 'wb') as wf:
pickle.dump(obj, wf)
# 反序列化
with open('2.txt', 'rb') as rf:
data = rf.read()
o1 = pickle.loads(data)
print(o1, type(o1))
with open('2.txt', 'rb') as rf:
data = rf.read()
o1 = pickle.loads(data)
print(o1, type(o1))
rf.seek(0, 0) # 游标移到开头出现读
o2 = pickle.load(rf)
print(o2, type(o2))
```
o2 = pickle.load(rf)
print(o2, type(o2))
```
三。hashlib
# 不可逆加密:没有解密的加密方式 md5
# 解密方式:碰撞解密
# 加密的对象:用于传输的数据(字符串类型数据)
# 一次加密:
# 1.获取加密对象 hashlib.md5() => lock_obj
# 2.添加加密数据 lock_obj.update(b'...') ... lock_obj.update(b'...')
# 3.获取加密结果 lock.hexdigest() => result
# 1.获取加密对象 hashlib.md5() => lock_obj
# 2.添加加密数据 lock_obj.update(b'...') ... lock_obj.update(b'...')
# 3.获取加密结果 lock.hexdigest() => result
lock = hashlib.md5(b'...')
lock.update(b'...')
# ...
lock.update(b'...')
res = lock.hexdigest()
print(res)
lock.update(b'...')
# ...
lock.update(b'...')
res = lock.hexdigest()
print(res)
# 加盐加密
# 1.保证原数据过于简单,通过复杂的盐也可以提高解密难度
# 2.即使被碰撞解密成功,也不能直接识别盐与有效数据
lock_obj = hashlib.md5()
lock_obj.update(b'goodgoodstudy')
lock_obj.update(b'123')
lock_obj.update(b'daydayup')
res = lock_obj.hexdigest()
print(res)
# 了了解:其他算法加密
lock_obj = hashlib.sha3_256(b'1')
print(lock_obj.hexdigest())
lock_obj = hashlib.sha3_512(b'1')
print(lock_obj.hexdigest())
```
四。hmac
import hmac
# hmac.new(arg) # 必须提供一个参数
cipher = hmac.new('加密的数据'.encode('utf-8'))
print(cipher.hexdigest())
cipher = hmac.new('前盐'.encode('utf-8'))
cipher.update('加密的数据'.encode('utf-8'))
print(cipher.hexdigest())
cipher.update('加密的数据'.encode('utf-8'))
print(cipher.hexdigest())
cipher = hmac.new('加密的数据'.encode('utf-8'))
cipher.update('后盐'.encode('utf-8'))
print(cipher.hexdigest())
cipher.update('后盐'.encode('utf-8'))
print(cipher.hexdigest())
cipher = hmac.new('前盐'.encode('utf-8'))
cipher.update('加密的数据'.encode('utf-8'))
cipher.update('后盐'.encode('utf-8'))
print(cipher.hexdigest())
```
cipher.update('加密的数据'.encode('utf-8'))
cipher.update('后盐'.encode('utf-8'))
print(cipher.hexdigest())
```
五。shutil
# 基于路径的文件复制:
shutil.copyfile('source_file', 'target_file')
# 基于流的文件复制:
with open('source_file', 'rb') as r, open('target_file', 'wb') as w:
shutil.copyfileobj(r, w)
# 递归删除目标目录
shutil.rmtree('target_folder')
with open('source_file', 'rb') as r, open('target_file', 'wb') as w:
shutil.copyfileobj(r, w)
# 递归删除目标目录
shutil.rmtree('target_folder')
# 文件移动
shutil.move('old_file', 'new_file')
shutil.move('old_file', 'new_file')
# 文件夹压缩
# file_name:被压缩后形成的文件名 format:压缩的格式 archive_path:要被压缩的文件夹路径
shutil.make_archive('file_name', 'format', 'archive_path')
# file_name:被压缩后形成的文件名 format:压缩的格式 archive_path:要被压缩的文件夹路径
shutil.make_archive('file_name', 'format', 'archive_path')
# 文件夹解压
# unpack_file:被解压文件 unpack_name:解压后的名字 format解压格式
shutil.unpack_archive('unpack_file', 'unpack_name', 'format')
```
# unpack_file:被解压文件 unpack_name:解压后的名字 format解压格式
shutil.unpack_archive('unpack_file', 'unpack_name', 'format')
```
六。shelve
# 将序列化文件操作dump与load进行封装
shv_dic = shelve.open("target_file") # 注:writeback允许序列化的可变类型,可以直接修改值
# 序列化:存
shv_dic['key1'] = 'value1'
shv_dic['key2'] = 'value2'
# 文件这样的释放
shv_dic.close()
shv_dic.close()
shv_dic = shelve.open("target_file", writeback=True)
# 存 可变类型值
shv_dic['info'] = ['原数据']
# 存 可变类型值
shv_dic['info'] = ['原数据']
# 取 可变类型值,并操作可变类型
# 将内容从文件中取出,在内存中添加, 如果操作文件有writeback=True,会将内存操作记录实时同步到文件
shv_dic['info'].append('新数据')
# 将内容从文件中取出,在内存中添加, 如果操作文件有writeback=True,会将内存操作记录实时同步到文件
shv_dic['info'].append('新数据')
# 反序列化:取
print(shv_dic['info']) # ['原数据', '新数据']
print(shv_dic['info']) # ['原数据', '新数据']
shv_dic.close()
```
```