Python删除文件及进行文件夹压缩

示例效果:

项目编译发布后,删除部分配置文件,然后做成发布文件的压缩包。

# -*- coding: UTF-8 -*-
import os,sys  
import zipfile
import datetime,time

def getToday_yyyyMMdd():
    #return time.strftime("%Y%m%d %H:%M:%S",time.localtime(time.time()))
    return time.strftime("%Y%m%d",time.localtime(time.time()))

def remove_noneed_files(startdir):
    if(os.path.exists(startdir+"\\appsettings.json")):
        os.remove(startdir+"\\appsettings.json")
    #if(os.path.exists(startdir+"\\nlog.config")):
        #os.remove(startdir+"\\nlog.config")
    if(os.path.exists(startdir+"\\nlog.Development.config")):
        os.remove(startdir+"\\nlog.Development.config")
    #if(os.path.exists(startdir+"\\web.config")):
        #os.remove(startdir+"\\web.config")

def zip_yasuo(startdir,file_news):
    z = zipfile.ZipFile(file_news,'w',zipfile.ZIP_DEFLATED) 
    for dirpath, dirnames, filenames in os.walk(startdir):
        fpath = dirpath.replace(startdir,'')
        fpath = fpath and fpath + os.sep or ''
        for filename in filenames:
            z.write(os.path.join(dirpath, filename),fpath+filename)
    z.close()
    
if __name__=="__main__":
    print("run start")
    startdir = "D:\\Projects\\Deploy"  
    file_news = 'C:\\Users\admin\\Desktop\\Deploy'+getToday_yyyyMMdd()+'.zip' 
    remove_noneed_files(startdir)
    zip_yasuo(startdir,file_news)
    print("run finished")
    #os.system('pause')

猜你喜欢

转载自www.cnblogs.com/freeliver54/p/9034903.html