栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python | 文件/文件夹的压缩及解压缩和信息读取

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python | 文件/文件夹的压缩及解压缩和信息读取

本文介绍如何压缩单个或多个文件,或者文件夹下的所有文件;如何解压缩压缩文件中的单个文件或所有文件;如何读取压缩文件的信息。


Python | 压缩文件/文件夹及解压缩

可行库读取信息

zipfile 压缩

zipfile

指定单个文件或多个文件指定文件夹下的所有文件添加文件或文件夹 shutil 解压

zipfile

指定压缩包中的指定文件或所有文件 参考链接


可行库

用于压缩文件/文件夹或解压缩的可行的几种第三方库

库名说明
zipfile
tarfiletarfile的用法和zipfile大同小异,详情查看这里
shutil详情见官方文档,其中需注意的是shutil.make_archive不是线程安全的。

读取信息 zipfile

  • 读取目标路径下的zip file并以zip_file来存储
    fromPath = './TEST/output.zip'
    zip_file = zipfile.ZipFile(fromPath)
  • 压缩文件中的所有文件
    fileList = zip_file.namelist()
  • 某文件压缩前后大小
    某文件为file, file = fileList[2]
    —— 压缩前文件大小为b_size = zip_file.getinfo(file).file_size
    —— 压缩后文件大小为a_size = zip_file.getinfo(file).compress_size
    压缩

    此处总结如何使用上述提到的第三方库来对相应文件/文件夹进行压缩打包。

    zipfile

    此处总结如何使用zipfile压缩单个或多个文件,指定文件夹下的所有文件,又或者添加文件或整个文件夹到指定zip文件

    指定单个文件或多个文件
    import zipfile
    import os
    
    # 1. define target folder and target path to export zip file
    fromPath1 = './test.py'
    fromPath2 = './DataAnalysis/Pandas/RawData.xlsx'
    toPath = './Test/output.zip'
    
    # 2. check if target path to export output.zip file exists: if yes, pass; if not, pass;
    toFolder, toFilename = os.path.split(toPath)
    if not os.path.exists(toFolder):
        os.mkdir(path=toFolder)
    toFolder, toFilename = os.path.split(toPath)
    
    # 3.
    with zipfile.ZipFile(toPath, 'w') as Export:
        Export.write(fromPath1)
        Export.write(fromPath2)
    

    定义被压缩打包的目标文件所在路径,比如这里的fromPath1和fromPath2

    判断目标路径toFolder是否存在:
    如果存在,进行下一步;如果不存在,创建toFolder。

    将对应fromPath1和fromPath2的文件以Export写入toPath的output.zip


    指定文件夹下的所有文件
    # 1. define target folder and target path to export zip file
    fromPath = './DataAnalysis/Pandas'                          
    toPath = './Test/output.zip'              
    
    # 2. check if target path to export output.zip file exists: if yes, pass; if not, pass;
    toFolder, toFilename = os.path.split(toPath)
    if not os.path.exists(toFolder):
        os.mkdir(path=toFolder)
    
    # 3. check if target path is for a file or a folder:
    with zipfile.ZipFile(toPath, 'w') as Export:
        # 3.1 if file: write file in target path
        if os.path.isfile(fromPath):
            Export.write(filename=fromPath)
        # 3.2 if folder: write files under folder into target path
        if os.path.isdir(fromPath):
            for root, dirs, files in os.walk(top=fromPath):
                for singleFile in files:
                    if singleFile != toFilename:
                        filepath = os.path.join(root, singleFile)
                        Export.write(filename=filepath)
    

    定义被压缩打包的目标文件夹,和输出压缩zip文件的目标文件名及所在路径。

    判断目标路径toFolder是否存在:
    如果存在,进行下一步;如果不存在,创建toFolder。

    判断目标路径fromPath为文件所在或文件夹所在路径:
    如果为文件,则按指定单个文件或多个文件所示的方法写入
    如果为文件夹,则轮询文件夹路径并将其下级文件写入


    添加文件或文件夹
    import zipfile
    import os
    
    fromPath = './test.py'
    toPath = './Test/output.zip'
    
    with zipfile.ZipFile(toPath, 'a') as Add:
        if os.path.isfile(fromPath):
            Add.write(fromPath)
        if os.path.isdir(fromPath):
            for root, dirs, files in os.walk(fromPath):
                for singleFile in files:
                    filepath = os.path.join(root, singleFile)
                    Add.write(filepath)
    

    定义需要被添加文件的所在路径,和压缩zip文件所在路径。

    判断目标路径toFolder是文件还是文件夹:
    如果是文件,以指定单个文件或多个文件中所介绍方法写入Add; 如果是文件夹,以指定文件夹下的所有文件中所介绍方法写入Add


    shutil

    此处总结如何使用shutil归档指定文件,或指定文件夹下的所有文件,为指定输出格式。

    import shutil
    
    fromPath = 'DataAnalysis/Pandas'
    toPath = './Test/output'
    
    shutil.make_archive(toPath, 'zip', fromPath)
    

    定义需要被归档的文件夹所在路径(也可以是单个或多个文件的路径),和存储归档文件的目标路径。


    解压

    此处总结如何使用上述提到的第三方库来对相应文件/文件夹进行解压缩。

    zipfile 指定压缩包中的指定文件或所有文件
    fromPath = './Test/output.zip'
    toPath = './ZIP'
    pwd = 'password'
    
    if not os.path.exists(toPath):
        os.mkdir(toPath)
    
    with zipfile.ZipFile(fromPath, 'r') as import:
    	# check file list of target zip file;  
    	print('File List: ', import.namelist()) 
    	
    	# read first file in file list  
    	print(import.read(import.namelist()[0]))   
    	
    	# unzip 2nd file in namelist() to path  
    	import.extract(path=toPath, member=import.namelist()[1], pwd=pwd)
    	
    	# unzip all in namelist() to path    
        z.extractall(path=toPath, pwd=pwd)                                                       
    

    读取fromPath,可以通过namelist()以列表的形式打印出output.zip文件中的所有文件名

    可以通过namelist来查看压缩文件中有哪些文件。
    可以通过read()读取namelist()中存在的文件的内容。

    可以通过extract(member=import.namelist()[x])来解压缩单个或多个文件到指定当前路径toPath,又或者以extractall来解压缩所有的文件到上述路径下。


    参考链接

    写本文时有参考以下链接:

    python 分离文件名和路径 以及 分离文件名和后缀
    使用Python实现文件压缩和解压
    python中zipfile、tarfile压缩文件模块的使用
    【zipfile】Python实现将文件打包为zip压缩包 & 解压
    python zipfile 打包文件夹,压缩文件夹为zip包
    Python3 错误:PermissionError: [Errno 13] Permission denied 如何解决?「xsl,csv」成功解决
    Python报错:PermissionError: [Errno 13] Permission denied解决方案详解
    shutil — 高阶文件操作¶

  • 转载请注明:文章转载自 www.mshxw.com
    本文地址:https://www.mshxw.com/it/700613.html
    我们一直用心在做
    关于我们 文章归档 网站地图 联系我们

    版权所有 (c)2021-2022 MSHXW.COM

    ICP备案号:晋ICP备2021003244-6号