tarfile壓縮模組

江寒雨發表於2024-03-07

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
"""

相關文章