• python 压缩与解压文件


    文件copy模块shutil

    高级的文件、文件夹、压缩包处理模块
    shutil.copyfileobj() 将文件内容拷贝到另一个文件中
    shutil.copyfile() 拷贝文件

    import shutil
    shutil.copyfileobj(open('day1.py',encoding='utf-8'),open('111.py','w',encoding='utf-8'))
    shutil.copyfile('day1.py','123.py')
    
    • 1
    • 2
    • 3

    shutil.copymode() 仅拷贝权限
    shutil.copystat() 仅拷贝状态的信息
    shutil.copy() 拷贝文件和权限
    shutil.copy2() 拷贝文件和转态
    shutil.copytree(‘’,’’,ignore=shutil.ingore_patterns(“.py,new”)) 递归地去拷贝文件夹
    shutil.rmtree() 递归地去删除文件
    shutil.move(A,B) A移动文件到B下
    shutil.make_archive(base_name(压缩包的名字或者给一下要保存的路径),format(压缩包的类型:zip,tar,bztar,gztar),root_dir(要压缩的文件夹路径),owner(用户,默认当前用户),group(组,默认当前组),logger(用于记录日志,通常是logging.Logger对象))

    import shutil
    
    shutil.make_archive('tang1','zip','../模块')
    
    • 1
    • 2
    • 3

    在这里插入图片描述

    Zipfile(压缩与解压)

    import zipfile
    import os
    b = []
    a = zipfile.ZipFile("xxx1.zip",'w')
    a.write('day2.py')
    for roots,dirs,files in os.walk("../函数"): # 遍历这个目录,目录下的每一个文件夹(包含它自己)
    ,产生3-元组 (dirpath, dirnames, filenames)【文件夹路径, 文件夹名字, 文件名】
        for name in files:
            b.append(os.path.join(roots,name)) # 拼接路径+文件名
    for i in b:
        a.write(i)
        print(b)
    a.close()
    
    # 解压
    a = zipfile.ZipFile("xxx1.zip",'r')
    a.extractall("tt")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    在这里插入图片描述

    Tarfile(压缩与解压)

    方法与上面类似

    import tarfile
    
    a = tarfile.open("a1.tar", "w")
    '''
    TarFile.add(name, arcname=None, recursive=True, exclude=None, *, filter=None)
    
    将指定文件加入包内。
    arcname参数用于变换路径和文件名。
    默认情况下,文件夹会被递归的加入包内,除非recursive参数设为False。
    filter参数指向一个方法,该方法用来过滤哪些文件不会被打入包内,不被打包的就返回个None,会的就返回tarinfo本身,
    该方法为3.2版本新增,同时废弃原有的exclude方法。
    '''
    a.add('day1.py',arcname='day1___1.py')
    a.close()
    
    # 解压
    a = tarfile.open("a1.tar", "r")
    a.extractall("xx")
    a.close()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    在这里插入图片描述

  • 相关阅读:
    在云服务器上安装配置和调优Zerotier服务器的详细教程
    SolidWorks二次开发语法技巧及基础
    网站一直被黑客攻击,我该如何反击
    X.509 V3证书的签发与验证
    【面试高频题】二叉树“神级遍历“入门
    REDIS学习笔记(一):基础与安装
    Keepalived
    Java 注解及其底层原理
    数据挖掘与机器学习:数据变换
    s3fs挂载多个桶或普通多目录通过NFS共享踩坑
  • 原文地址:https://blog.csdn.net/LOVE_jianshen/article/details/126813543