使用Python管理压缩包
一、 使用tarfile库读取与创建tar包#
1. 创建tar包
1 2 3 4 5 6 | In [ 1 ]: import tarfile In [ 2 ]: with tarfile. open ( 'demo.tar' ,mode = 'w' ) as out: ...: out.add( '1.txt' ) ...: out.add( '2.txt' ) ...: |
2. 读取tar包
1 2 3 4 5 6 7 8 | In [ 1 ]: import tarfile In [ 2 ]: with tarfile. open ( 'demo.tar' ) as t: ...: for file in t.getmembers(): ...: print ( file .name) ...: 1.txt 2.txt |
3. 创建压缩包
1 2 3 | In [ 8 ]: with tarfile. open ( 'demo.tar.gz' ,mode = 'w:gz' ) as out: ...: out.add( '1.txt' ) ...: out.add( '2.txt' ) |
4. 读取压缩包
1 2 3 4 5 6 | In [ 10 ]: with tarfile. open ( 'demo.tar.gz' ,mode = 'r:gz' ) as out: ...: for f in out.getmembers(): ...: print (f.name) ...: 1.txt 2.txt |
5. 提取单个或者所有文件
1 2 3 4 5 6 7 | In [ 14 ]: with tarfile. open ( 'demo.tar.gz' ,mode = 'r:gz' ) as out: ...: out.extract( '1.txt' ) ...: In [ 15 ]: with tarfile. open ( 'demo.tar.gz' ,mode = 'r:gz' ) as out: ...: out.extractall() ...: |
二、使用zipfile库创建和读取压缩包#
1. 创建zip文件
1 2 3 4 5 6 7 8 9 | In [ 19 ]: import zipfile In [ 20 ]: newZip = zipfile.ZipFile( 'demo.zip' , 'w' ) In [ 21 ]: newZip.write( '1.txt' ) In [ 22 ]: newZip.write( '2.txt' ) In [ 23 ]: newZip.close() |
2. 读取zip文件
1 2 3 4 | In [ 24 ]: newZip = zipfile.ZipFile( 'demo.zip' ) In [ 25 ]: newZip.namelist() Out[ 25 ]: [ '1.txt' , '2.txt' ] |
3. 解压zip文件
1 2 3 4 | In [ 27 ]: newZip.extract( '1.txt' ) Out[ 27 ]: '/tmp/test/1.txt' In [ 28 ]: newZip.extractall() |
三、 使用shutil管理压缩包#
1 2 3 4 5 6 7 8 9 10 11 | In [ 40 ]: import shutil In [ 41 ]: shutil.make_archive( 'demo' , 'zip' ) Out[ 41 ]: 'demo.zip' In [ 42 ]: shutil.make_archive( 'demo' , 'gztar' ) Out[ 42 ]: 'demo.tar.gz' In [ 43 ]: shutil.unpack_archive( 'demo.tar.gz' ) In [ 44 ]: shutil.unpack_archive( 'demo.zip' ) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了