Python:實現文件歸檔
阿新 • • 發佈:2018-03-15
目錄 備份 實現功能:
將E:\123文件備份至E:\backup 文件夾下,以當前的日期為子目錄存放備份後的文件
1 #! /usr/bin/python 2 #Filename:backup.py 3 #功能說明:備份文件,以當前日期為子目錄存放備份後的文件 4 5 import os 6 import time 7 #要備份的目錄,可在此列表中增加 8 source = [r‘E:\123‘] 9 10 #備份文件存放的目錄 11 target_dir = ‘E:\\backup\\‘ 12 13 #取當前時間為備份子目錄名 14 today = target_dir + time.strftime(‘%Y%m%d‘) 15 now = time.strftime(‘%H%M%S‘) 16 17 #在備份文件名中加入註釋 18 comment = input(‘Enter a comment:‘) 19 if len(comment) == 0: 20 target = today + os.sep + now + ‘.zip‘ 21 else: 22 target = today + os.sep + now + ‘_‘ + 23 comment.replace(‘ ‘,‘_‘) + ‘.zip‘ 24 25 #如果目標目錄不存在就創建 26 if not os.path.exists(today): 27 os.mkdir(today) 28 print (‘Sucessfully created directoy‘,today) 29 30 #備份命令,可替換為7z,linux下可改為tar等 31 zip_command = "winrar a %s %s"%(target, ‘ ‘.join(source)) 32 33 #執行命令 34 if os.system(zip_command) == 0: 35 print(‘Successful backup to‘,target) 36 else: 37 print(‘Backup failed‘)
註意:
pycharm運行出現報錯信息如下:
"winrar" 不是內部或外部命令,也不是可運行的程序或批處理文件。
Backup failed
解決方法:
將winrar的安裝路徑,添加到環境變量path內即可。
Python:實現文件歸檔