• 快速生成指定大小的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)
    

      

  • 相关阅读:
    高阶篇:1.2)材料和工艺的选择
    高阶篇:4.1.1)QFDI(客户需求转换为设计要求)
    高阶篇:4)可靠性设计-总章
    高阶篇:1.5)如何选择更好的概念-Pugh矩阵法
    知识点篇:2)产品结构设计目标的分类
    高阶篇:1.1)竞品(标杆产品)的拆解和分析benchmarking
    支持向量机
    机器学习概述
    HDU_oj_2055 An easy problem
    HDU_oj_2054 A==B ?
  • 原文地址:https://www.cnblogs.com/relustarry/p/16287659.html
Copyright © 2020-2023  润新知