第十八章:常用模块

it2025-10-29  14

跨文件夹移动文件

import osimport sysBASE_DIR = os.path.dirname(os.path.dirname(__file__))sys.path.append(BASE_DIR)​def move_file(file, folder):    if not (os.path.exists(file) and os.path.isfile(file)):        print('文件不存在或非法')        return False    if not os.path.exists(folder):        os.makedirs(folder)    file_name = os.path.split(file)[1]    # file_name = os.path.basename(file)    new_file = os.path.join(folder, file_name)​    with open(file, 'rb') as rf, open(new_file, 'wb') as wf:        for line in rf:            wf.write(line)​    os.remove(file)​# 将目标文件夹下的目标文件移动到指定文件夹下file = os.path.join(BASE_DIR, 'part5', 'mm.py')folder = os.path.join(BASE_DIR, 'part6', 'abc')move_file(file, folder)

 

 

递归删除的思路

def delete_dir(folder):    for path in os.listdir(folder):        # 如果path是文件夹 delete_dir(path)        # 如果是文件os.remove(path)        pass    # for走完了代表folder内部删空了,可以删folder

 

递归遍历打印目标路径中所有的txt文件

def print_txt(folder):    if not os.path.exists(folder) or os.path.isfile(folder):        return    for path in os.listdir(folder):        file_path = os.path.join(folder, path)        if os.path.isfile(file_path) and file_path.endswith('.txt'):            print(path)        elif os.path.isdir(file_path):            print_txt(file_path)  # 递归​​target_path = os.path.join(BASE_DIR, 'part6', 'target')print_txt(target_path)

 

项目开放周期

'''1.调研2.需求分析3.架构师完成项目demo,完成项目架构4.分工5.写代码6.白盒黑盒测试7.项目审核发布 => 项目 -> 产品'''​'''bin: 可执行文件,入口,入口也可以放在项目根目录下core: 核心代码db:数据库相关文件interface:接口lib:包、模块、第三方文件夹log:日志setting:配置static:静态文件''' # 递归遍历 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) # 递归删除 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) # 验证码 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 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 def random_code2(num):     target = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'     code_list = random.sample(target, num)     return ''.join(code_list) r1 = random_code2(18) print(r1)

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_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))

 

 

pickle

# 为什么有很多序列化和反序列化模块# 因为程序中会出现各种各样的对象,如果要将这些对象持久化存储,必须先序列化# 只有序列化存储后,必须有对应的反序列化,才能保证存储的数据能被重新读取使用​# 什么是序列化:对象 => 字符串# 为什么序列化:存 或 传# 为什么要反序列化:再次使用# 为什么有很多序列化模块:存与取的算法可以多种多样,且要配套​import pickleobj = {"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))​    rf.seek(0, 0)  # 游标移到开头出现读    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​lock = hashlib.md5(b'...')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 = hmac.new('加密的数据'.encode('utf-8'))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())

 

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')​# 文件移动shutil.move('old_file', 'new_file')​# 文件夹压缩# 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')

 

 

shelve

# 将序列化文件操作dump与load进行封装shv_dic = shelve.open("target_file")  # 注:writeback允许序列化的可变类型,可以直接修改值# 序列化:存shv_dic['key1'] = 'value1'shv_dic['key2'] = 'value2'​# 文件这样的释放shv_dic.close()​​​shv_dic = shelve.open("target_file", writeback=True)# 存 可变类型值shv_dic['info'] = ['原数据']​# 取 可变类型值,并操作可变类型# 将内容从文件中取出,在内存中添加, 如果操作文件有writeback=True,会将内存操作记录实时同步到文件shv_dic['info'].append('新数据')​# 反序列化:取print(shv_dic['info'])  # ['原数据', '新数据']​shv_dic.close()

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/haojunliancheng/p/10833867.html

相关资源:Freescale系列单片机常用模块与综合系统设计实例精讲
最新回复(0)