【原】Python用例:将指定文件或目录打包成zip文件

时间:2022-07-20 00:53:18

【原】Python用例:将指定文件或目录打包成zip文件

【原】Python用例:将指定文件或目录打包成zip文件

 #This Demo is used to compress files to .zip file
 #Base on Windows

 import os
 import time

 #The files or directories you want to compress
 source=['e:\\log2.log',r'e:\2013_8_15_S1.dmp',r'e:\Reflector']

 #The target directory you want to place the zip file
 target_dir='e:\\mybackup\\'

 today=target_dir+time.strftime('%Y%m%d')
 now=time.strftime('%H%M%S')

 # if the path not exist, then create it
 if not os.path.exists(today):
     os.mkdir(today)
     print('Successfully created directory',today)

 comments=input("Please add some comments for this backup: ")

 if  len(comments)==0:
     target=today +os.sep+now+'.zip'
 else:
      target=today +os.sep+now+'_'+comments.replace(" ","_")+'.zip'

 zip_command = '"C:\\Program Files\\WinRAR\\Rar.exe" a %s %s' %(target," ".join(source))

 if os.system(zip_command) == 0:
     print ('Successful backup to', target)

 else:
     print('Backup Failed')