python实现zip压缩

准备写个备份数据的脚本,虽然linux下有zip等软件,但是python有自带zipfile类库,实现起来并不复杂,权当练手.

#!/usr/bin/python
import os
import zipfile
import sys
import platform
    
global line
if platform.system() == "Windows":
    line = "\\"
else:
    line = "/"
    
def zip_dir(path,spath,zip_obj,zip_file):
    if os.path.exists(path):
        tmp = os.listdir(path + line)
        for i in range(0,len(tmp)):
            nowfile = path+tmp[i]
            if  os.path.isfile(nowfile):
                if nowfile != zip_file:
                    zip_obj.write(nowfile,nowfile[len(spath):len(nowfile)])
                    print("File:%s Is compressed" %(nowfile))
            else:
                zip_dir(nowfile+line,spath,zip_obj,zip_file)
    else:
        print("Directory:%s does not exist" %(path))
        return -1
    return 0
    
if len(sys.argv) > 2:
    zfile = sys.argv[1]
    path = sys.argv[2]+line
    if os.path.exists(os.path.dirname(zfile)) == False:
        zfile =  os.path.join(os.getcwd(), zfile)
    z = zipfile.ZipFile(zfile,"w")
    zip_dir(path,path,z,zfile)
    z.close()
    sys.exit
else:
    print("Parameter Error")
    print("Parameter Is : zip.py [zipfile] [directory]")
    sys.exit

调用参数为 :

[脚本文件]  [目标ZIP文件] [要压缩的目录或者文件]

标签: python, zip

添加新评论