压缩当前路径 - 压缩备份

#!/usr/bin/python
#Pythth2.7x, Python3x
#coding: utf-8 
import os
import zipfile
import glob
import time

import win32con, win32api, os

def get_myfilelist(os_dir,wanted=1):
    '''
    os_dir='E:\\BACKUP\\BlueDict\\'
    '''
    all_dirs=[os_dir+'\\']
    all_files=[]
    for (croot, dirs, files) in os.walk(os_dir):
        #print(croot, dirs, files)
        for d in dirs:
            all_dirs.append(croot+'\\'+d+'\\')
        for f in files:
            all_files.append(croot+'\\'+f)

    empty_dirs=[]
    for folder in all_dirs:
        if not os.listdir(folder): #空文件夹
            empty_dirs.append(folder)

    ### 获取需要的列表 ###
    if wanted==1:
        return empty_dirs+all_files
    elif wanted==2:
        return empty_dirs
    elif wanted==3:
        return all_files
    elif wanted==4:
        return all_dirs+all_files






def cwd_zipping():
    os_cwd=os.getcwd()
    print(os_cwd)
    print('===========')

    time_string='____'+time.strftime("%Y-%m-%d, %H-%M-%S", time.localtime())
    zipfilename="%s%s.zip"%(os_cwd, time_string)

    zf=zipfile.ZipFile(zipfilename, "w", zipfile.ZIP_DEFLATED)
    l=get_myfilelist(os_dir=os_cwd, wanted=1)
    for i in l:
        i_=i[0:len(os_cwd)].split('\\')[-1]+'\\'+i[len(os_cwd):len(i)]
        zf.write(i,i_)
        print(i_)
    zf.close()
    print('===========')



if __name__ =='__main__':
    cwd_zipping()

你可能感兴趣的:(Python)