tarfile压缩模块
创建文件
import tarfile
"""
此过程只是创建压缩包 并不打包数据
"""
# 创建压缩包
fp = tarfile.open("ceshi.tar","w",encoding="utf-8")
# 写入文件
"""add(路径,别名)"""
fp.add("2","2tmp")
fp.add("lianxi2","lianxi")
# close file
fp.close()
压缩文件
gz算法
import tarfile
"""
可以直接通过tar算法打包压缩
"""
# 创建压缩包
fp = tarfile.open("ceshi1.tar.gz","w",encoding="utf-8")
# 写入文件
fp.add("2","2tmp")
fp.add("lianxi2","lianxi")
# close file
fp.close()
bz算法
import tarfile
"""
可以直接通过tar算法打包压缩
"""
# 创建压缩包
fp = tarfile.open("ceshi1.tar.bz2","w:bz2",encoding="utf-8")
# 写入文件
fp.add("2","2tmp")
fp.add("lianxi2","lianxi")
# close file
fp.close()
解压文件
tf = tarfile.open("ceshi0930_1.tar.gz","r",encoding="utf-8")
""" extract(文件,路径) 解压单个文件"""
tf.extract("chown","ceshi0930_1")
""" extract(路径) 解压所有文件"""
tf.extractall("ceshi0930_1_2")
tf.close()
追加文件
tf = tarfile.open("ceshi0930_0.tar","a",encoding="utf-8")
tf.add("/bin/mkdir","mkdir")
tf.close()
with改造
with tarfile.open("ceshi0930_0.tar","a",encoding="utf-8") as tf:
tf.add("/bin/mkdir","mkdir234")
查看文件
with tarfile.open("ceshi0930_0.tar","r",encoding="utf-8") as tf:
lst = tf.getnames() # return 文件 list
print(lst)
追加文件改造
import tarfile
import os
import shutil
"""
可以直接通过tar算法打包压缩
"""
with tarfile.open("2.tar.gz","w:gz",encoding="utf-8") as tf:
tf.add("1.txt")
tf.add("2.txt")
"""
2.tar.gz 文件生成
"""
fileSize = os.path.getsize("2.tar.gz")
print(fileSize) # out 3069
"""
1.把已经压缩的包进行解压
2.把要追加的内容放进去
3.过滤文件重新压缩
"""
# 记录压缩包所在的绝对路径
pathvar1 = os.path.abspath("2.tar.gz")
# 要解压到哪个文件夹中(绝对路径)
pathvar2 = os.path.join(os.getcwd(),"tmp")
print(pathvar1)
print(pathvar2)
# 1.把已经压缩的包进行解压
with tarfile.open(pathvar1,"r",encoding="utf-8") as tf:
tf.extractall(pathvar2) # 解压的位置
# 2.把要追加的内容放进去
shutil.copy("3.txt" , pathvar2)
# 3.过滤文件重新压缩
# 查看文件夹当中有什么文件
lst = os.listdir(pathvar2)
print(lst) # ['1.txt', '2.txt', '3.txt']
with tarfile.open(pathvar1,"w:bz2",encoding="utf-8") as tf:
for i in lst:
if i != "1.txt":
# 拼凑成所需文件的完整的绝对路径
abs_path = os.path.join(pathvar2,i)
# 剩下的都要压缩
"""add(路径,别名)"""
tf.add(abs_path,i)
"""
C:\Users\wbcde\Desktop\pythonProject1\测试\tmp\2.txt
C:\Users\wbcde\Desktop\pythonProject1\测试\tmp\3.txt
"""
标签:fp,utf,tar,压缩,tarfile,add,模块,tf
From: https://www.cnblogs.com/wbcde116/p/18059381