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

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

Last Modified: 2022 / 6 / 17



可行库

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

库名说明
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)
### or
# Export = zipfile.ZipFile(toPath, 'w')
# Export.write(fromPath1)
# Export.write(fromPath2)
# Export.close()

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

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

将对应fromPath1fromPath2的文件以Export写入toPathoutput.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; <class 'list'> 
	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来解压缩所有的文件到上述路径下。


tarfile

tarfile的解压用法可参考 1


指定压缩包中所有文件

fromPath = './File'

tar = tarfile.open(fromPath, 'r')
tar.extractall()
tar.close()                                                    

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

可以通过extractall来解压缩所有的文件在当前路径下。


参考链接

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

python创建文件和文件夹
python 分离文件名和路径 以及 分离文件名和后缀

可行库

文件导出与下载(Excel,Zip)等几种方式
shutil — 高阶文件操作¶

压缩

Python 标准库 zipfile 将文件夹加入压缩包
使用Python实现文件压缩和解压
python中zipfile、tarfile压缩文件模块的使用
【zipfile】Python实现将文件打包为zip压缩包 & 解压
python zipfile 打包文件夹,压缩文件夹为zip包
Python3 错误:PermissionError: [Errno 13] Permission denied 如何解决?「xsl,csv」成功解决
Python报错:PermissionError: [Errno 13] Permission denied解决方案详解


  1. Python中使用tarfile压缩、解压tar归档文件示例(最新+全面=强烈推荐! ! !) ↩︎

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值