import os
import tarfile
def tarFiles():
folder = r'D:\proj\code'
tarTmp = os.path.join(r'D:\tmp', 'checkCode.tar.gz')
try:
if os.path.exists(tarTmp):
os.remove(tarTmp)
if not os.path.exists(folder):
raise('tar folder is not exist, folder: %s' % folder)
print('tar code file path: %s' % tarTmp)
tarf = tarfile.open(tarTmp,'w:gz') # 打开文件流
tarf.add(folder,arcname='',recursive=True) # 递归压缩指定目录
tarf.close()
except Exception as e:
print('tar file has failed, exception %s, trace: %s'%(e, traceback.format_exc()))
# 解压tar.gz文件到目标文件夹
def extractTarFiles():
extractFolder = r'D:\projectyCode'
tarTmp = os.path.join(r'D:\tmp', 'checkCode.tar.gz')
try:
if not os.path.exists(extractFolder):
os.mkdir(extractFolder)
if not os.path.exists(tarTmp):
raise('tar file is not exist,tar file %s' % tarTmp)
print('tar extract tar file %s into: %s' % (tarTmp,extractFolder))
tarf = tarfile.open(tarTmp,'r')
tarf.extractall(path=extractFolder) # 加压全部的文件到path
tarf.close()
except Exception as e:
print('tar file has failed, exception %s, trace: %s'%(e, traceback.format_exc()))
if __name__ == "__main__":
tarFiles()
extractTarFiles()
tarfile 压缩解压目录
最新推荐文章于 2023-03-07 08:42:58 发布