python 压缩成tar.gz,解压zip文件,删除文件

import os, tarfile
import shutil
import datetime
from zipfile import ZipFile
#一次性打包整个根目录。空子目录会被打包。
#如果只打包不压缩,将"w:gz"参数改为"w:"或"w"即可。
def make_targz(source_dir,output_filename):
    Status=1
    try:
        with tarfile.open(output_filename, "w:gz") as tar:
            tar.add(source_dir, arcname=os.path.basename(source_dir))
    except:
        Status=0
    return Status
def del_file(source_dir,file_type='files'):
    Status=1
    try:
        if file_type=='files':
            os.remove(source_dir)
        else:
            shutil.rmtree(source_dir)
        print('del success:',source_dir)
    except:
        Status=0
    return Status

  1.压缩 与删除

output_filename=r'C:\Users\zhoujun\Desktop\projects\test\压缩文件脚本\input\20220211.tar.gz'
source_dir=r'C:\Users\zhoujun\Desktop\projects\test\压缩文件脚本\input\20220211'
make_targz(source_dir,output_filename)
source_dir1=r'C:\Users\zhoujun\Desktop\projects\test\压缩文件脚本\input\20220211'
del_file(source_dir1)

 2.解压zip文件夹,包括修正文件夹名乱码问题

def recode(raw: str) -> str:
    '''编码修正'''
    try:
        return raw.encode('cp437').decode('gbk')
    except:
        return raw.encode('utf-8').decode('utf-8')

def unzipFun(source_zip,output_dir):
    #source_zip :zip文件绝对路径
    #output_dir :解压到路径
    file = ZipFile(source_zip)
    # 遍历压缩包内所有内容
    for file_or_path in file.namelist():
        # 若当前节点是文件夹
        if file_or_path.endswith('/') or file_or_path.endswith('\\'):
            try:
                # 基于当前文件夹节点创建多层文件夹
                os.makedirs(os.path.join(output_dir, recode(file_or_path)))
            except FileExistsError:
                # 若已存在则跳过创建过程
                pass
        # 否则视作文件进行写出
        else:
            # 利用shutil.copyfileobj,从压缩包io流中提取目标文件内容写出到目标路径
            with open(os.path.join(output_dir, recode(file_or_path)), 'wb') as z:
                # 这里基于Zipfile.open()提取文件内容时需要使用原始的乱码文件名
                shutil.copyfileobj(file.open(file_or_path), z)
source_zip=r'C:\Users\zhoujun\Desktop\projects\test\压缩文件脚本\input\2023.zip'
output_dir=r'C:\Users\zhoujun\Desktop\projects\test\压缩文件脚本\input'
unzipFun(source_zip,output_dir)

 

posted @ 2022-11-24 16:25  简单音乐  阅读(691)  评论(0)    收藏  举报