一个支持将多个文件夹分别压缩成zip文件的小程序工具

说明:

因为工作需要, 将多个目录单独进行文件压缩, 但是除了广告特别的的  '好压2345' 外都不支持. 受够了整天弹广告, 自己写了个简单小程序. 有需要的直接下载哦. 

python3.6 测试可用. 

 

import os, sys
import zipfile

ZipFile = zipfile.ZipFile


def zip_dir2file(directory):
    print("directory is", directory)
    if directory and os.path.exists(directory):
        abspath = os.path.abspath(directory)
        print(abspath, directory)
        if abspath != directory:
            print("not abs path", abspath, directory)
            return -2, None
    else:
        print("directory error")
        return -1, None
    items = os.listdir(directory)
    #print("list dir:", items)
    files = []
    for item in items:
        item = os.path.join(directory, item)
        #print("abs path item:", item)
        if os.path.isfile(item):
            #print(item, "is a file")
            files.append(item)
    zipfilename = os.path.dirname(directory)
    zipfilename = os.path.join(zipfilename, (os.path.basename(directory) + '.zip'))
    with ZipFile(zipfilename, 'w') as myzip:
        for file in files:
            #print("item:", file)
            myzip.write(file, arcname=os.path.basename(file))
    return 0, zipfilename


def zip_multi_dir_each_gen2file(directory):
    print("directory is", directory)
    if directory and os.path.exists(directory):
        abspath = os.path.abspath(directory)
        print(abspath, directory)
        if abspath != directory:
            print("not abs path", abspath, directory)
            return -2, None
    else:
        print("directory error")
        return -1, None

    items = os.listdir(directory)
    #print("list dir:", items)
    dirs = []
    for item in items:
        item = os.path.join(directory, item)
        #print("abs path item:", item)
        if os.path.isdir(item):
            print(item, "is a dir")
            dirs.append(item)
    success = []
    for d in dirs:
        ret = zip_dir2file(d)
        if ret[0]:
            print("error")
            return -1, None
        else:
            success.append(ret[1])
    print(f"zip total {len(success)} directorys")
    print(f"all generate files all:\n {success}")
    return 0, success


if __name__ == "__main__":
    usage = "usage: this app will zip multi directory each to a zipfile. \n app + directory. "
    if len(sys.argv) > 1:
        print("will zip directorys to file in:", sys.argv[1])
        zip_multi_dir_each_gen2file(sys.argv[1])
    else:
        print(usage)

 

你可能感兴趣的:(python,个人工作环境)