快速生成指定大小的zip文件

# -*- coding:utf-8 -*-
# 生成指定大小文件
import time
import os
import zipfile
import shutil

def creatfilesize(n, dirname):
    local_time = time.strftime("%Y%m%d%H%M%S", time.localtime())
    file_name = dirname + str(local_time)+".txt"
    bigFile= open(file_name, 'w')
    bigFile.seek(1024*1024*n)
    bigFile.write('test')
    #bigFile.write("test")
    bigFile.close()
    print('creat %s MB data' % n)
    return file_name

def creatzfile(filename, writefile):
    zfile = zipfile.ZipFile(filename, 'a', compression=zipfile.ZIP_STORED, allowZip64=True)   #写大文件,开启zip64
    zfile.write(writefile)
    zfile.close()

    size = float(os.path.getsize(filename))
    size_MB = size / (1024*1024)
    print('zipSize(MB):', size_MB)
    return size_MB

def delete_file(file_path):
    """
    删除文件下的文件
    """
    listdir = os.listdir(file_path)
    for i in listdir:
        os.remove(os.path.join(file_path, i))


def zip_dir(dirname, zipfilename):
    filelist = []
    if os.path.isfile(dirname):
        filelist.append(dirname)
    else:
        for root, dirs, files in os.walk(dirname):
            for name in files:
                filelist.append(os.path.join(root, name))

    zf = zipfile.ZipFile(zipfilename, "w", zipfile.ZIP_STORED, allowZip64=True)
    for tar in filelist:
        arcname = tar[len(dirname):]
        print('arcname', arcname)
        zf.write(tar, arcname)
    zf.close()

    size = float(os.path.getsize(zipfilename))
    size_MB = size / (1024 * 1024)
    print('zipSize(MB):', size_MB)
    return size_MB


if __name__ == '__main__':

    # n = input("输入你要生成的文件大小(单位为M):")
    # creatfilesize(n)
    zipfilename = 'out.zip'
    dirname = './data/'
    n = 23.4
    writefile = creatfilesize(n, dirname)    # 生成指定大小的txt文件
    num = 0
    while True:
        zipsize = zip_dir(dirname, zipfilename)
        num += 1
        if zipsize >= n:
            break
        shutil.copyfile(writefile, os.path.join(dirname, '_new%s.txt' % num))
    # 清理生成的文件
    delete_file(dirname)

    z = zipfile.ZipFile(zipfilename, "r")
    for filename in z.namelist():
        print(filename)

  

posted @ 2022-05-19 10:44  ReluStarry  阅读(51)  评论(0编辑  收藏  举报