首页 > 其他分享 >tar.gz打包压缩文件

tar.gz打包压缩文件

时间:2022-12-07 14:57:33浏览次数:40  
标签:tar flists gz 压缩文件 file path os

功能:

把某文件夹内的图片,视频打包压缩成.tar.gz文件, 并把文件随机重命名,生成对应的json文件

运行效果如下图:

 

 

 

 

"""
    功能:把文件夹内的所有文件打包压缩
"""

import os, tarfile
import random
import json
import string

import easygui

faceNums = 0

# 第一步获取目录图片文件名
def getImagesFilename(filepath):
    global faceNums
    '''
        函数功能:获取某目录下所有图片文件名
    '''

    flists = []
    if not os.path.isdir(filepath):
        print(f'{filepath}不是目录')
        return
    dirs = os.listdir(filepath)
    for file in dirs:
        if file.endswith(('.jpg', 'png', 'bmp', '.jpeg', '.gif', '.tiff', '.tga',
                          '.avi', '.wmv', '.mpg', '.mpeg', '.mov', '.rm', '.ram', '.flv', '.swf', '.mp4')):
            faceNums += 1
            flists.append(file)
    # print(faceNums, flists)
    return flists

# 逐个添加文件打包成tar.gz
def make_targz_one_by_one(output_filename, source_dir, flists, type):

    tar = tarfile.open(output_filename, "w:gz")
    ad_file = 'advert.json'
    advert_json = {"playlist": []}
    count = 1
    half_num = 0

    if flists:
        try:
            half_num = int(len(flists)/2)
        except:
            pass


    for file in flists:
        id = ''
        file_path = os.path.join(source_dir, file)
        # 重命名文件名,以防中文等非法字符
        _, ext = os.path.splitext(file)
        filename = ''.join(random.sample(string.ascii_letters, 16)) + ext
        tar.add(file_path, arcname=os.path.join('Advert\\media', filename))

        for i in range(0, 4):
            num = random.randint(0, 9)
            id += str(num)

        if type == 0:
            if count <= half_num:
                type_val = 1
            else:
                type_val = 2

        elif type == 1:
            type_val = 1

        elif type == 2:
            type_val = 2
        else:
            type_val = 2

        # json文件内容创建
        ad_dict = {
        "id": f"{id}",
        "type": type_val,
        "duration": 5,
        "url": f"/userdata/Advert/media/{filename}"}
        advert_json["playlist"].append(ad_dict)
        count += 1

    data = json.dumps(advert_json, ensure_ascii=False, indent=4)

    with open(ad_file, 'w', encoding='utf-8') as fw:
        fw.write(data)
    tar.add(os.path.join(os.getcwd(), ad_file), arcname=os.path.join('Advert\\conf', ad_file))

    tar.close()
    os.remove(ad_file)
    return 1

def start():
    tmp_file_name = 'Advert.tar.gz'
    size_sum = 0
    size_sum_gb = 0
    desktop_path = os.path.join(os.path.expanduser('~'), 'Desktop')
    # 弹出选择文件夹对话框
    ret = easygui.diropenbox('请选择一个广告文件所在文件夹', '浏览文件夹', desktop_path)

    if ret == None:
        return

    flists = getImagesFilename(ret)
    show_ad_filename = ''

    for file in flists:
        show_ad_filename +=  file + '\n'
        file_path = os.path.join(ret, file)
        file_size = os.path.getsize(file_path)
        size_sum += file_size

    if size_sum:
        size_sum = round(size_sum / 1024 / 1024, 2)
        size_sum_gb = int(size_sum / 1024)

    # 弹出选择广告类型的对话框
    message = easygui.buttonbox(f'广告文件夹:{ret}\n\n文件列表如下:\n{show_ad_filename}\n总文件数:{len(flists)}\t\t总大小:{size_sum}MB\n\n------ 请在下面选择广告模式 ------',
                                choices=['半屏', '全屏', '全屏和半屏混合'])
    if message == '半屏':
        type = 2
    elif message == '全屏':
        type = 1
    elif message == '全屏和半屏都有':
        type = 0
    else:
        return

    if size_sum_gb >= 1:
        easygui.msgbox(f'广告文件总大小不能超出1GB,请先检查!')
        return

    result = make_targz_one_by_one(tmp_file_name, ret, flists, type)

    if result == 1:
        easygui.msgbox(f'创建{tmp_file_name}完成')
    else:
        easygui.msgbox(f'创建{tmp_file_name}失败')

if __name__ == '__main__':
    start()

 

标签:tar,flists,gz,压缩文件,file,path,os
From: https://www.cnblogs.com/xiaojiaocx/p/16963056.html

相关文章