zoukankan      html  css  js  c++  java
  • 模块4

    递归遍历

    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代码 t'
    delete_folder(folder)

    验证码:random模块

    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:是python内部自己的序列化

    为什么有很多序列化和反序列化模块
    因为程序中会出现各种各样的对象,如果要将这些对象持久化存储,必须先序列化
    只有序列化存储后,必须有对应的反序列化,才能保证存储的数据能被重新读取使用

    什么是序列化:对象 => 字符串
    为什么序列化:存 或 传
    为什么要反序列化:再次使用
    为什么有很多序列化模块:存与取的算法可以多种多样,且要配套

    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)

    # 反序列化
    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()

  • 相关阅读:
    手脱UPX v0.89.6
    手脱ASPack v2.12
    为什么每次进入命令都要重新source /etc/profile 才能生效?
    解决maven update project 后项目jdk变成1.5
    关于dubbo服务的xml配置文件报错的问题
    dubbo实际应用中的完整的pom.xml
    部署Maven项目到tomcat报错:java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener【转】
    web.xml配置文件中<async-supported>true</async-supported>报错
    eclipse在线安装maven插件
    centos安装eclise启动报错
  • 原文地址:https://www.cnblogs.com/xinfan1/p/10833941.html
Copyright © 2011-2022 走看看