【原】Python用例:将指定文件或目录打包成zip文件
1 #This Demo is used to compress files to .zip file 2 #Base on Windows 3 4 import os 5 import time 6 7 #The files or directories you want to compress 8 source=['e:\\log2.log',r'e:\2013_8_15_S1.dmp',r'e:\Reflector'] 9 10 #The target directory you want to place the zip file 11 target_dir='e:\\mybackup\\' 12 13 14 today=target_dir+time.strftime('%Y%m%d') 15 now=time.strftime('%H%M%S') 16 17 # if the path not exist, then create it 18 if not os.path.exists(today): 19 os.mkdir(today) 20 print('Successfully created directory',today) 21 22 comments=input("Please add some comments for this backup: ") 23 24 if len(comments)==0: 25 target=today +os.sep+now+'.zip' 26 else: 27 target=today +os.sep+now+'_'+comments.replace(" ","_")+'.zip' 28 29 30 zip_command = '"C:\\Program Files\\WinRAR\\Rar.exe" a %s %s' %(target," ".join(source)) 31 32 33 if os.system(zip_command) == 0: 34 print ('Successful backup to', target) 35 36 else: 37 print('Backup Failed')