標籤:目錄 備份
實現功能:
將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:實現檔案歸檔