天天看點

Python:實作檔案歸檔

實作功能:

将E:\123檔案備份至E:\backup 檔案夾下,以目前的日期為子目錄存放備份後的檔案

#! /usr/bin/python
 #Filename:backup.py
 #功能說明:備份檔案,以目前日期為子目錄存放備份後的檔案
 import os
 import time
 #要備份的目錄,可在此清單中增加
 source = [r'E:\123']
 #備份檔案存放的目錄
 target_dir = 'E:\\backup\\'
 #取目前時間為備份子目錄名
 today = target_dir + time.strftime('%Y%m%d')
 now = time.strftime('%H%M%S')
 #在備份檔案名中加入注釋
 comment = input('Enter a comment:')
 if len(comment) == 0:
     target = today + os.sep + now + '.zip'
 else:
     target = today + os.sep + now + '_' + \
 comment.replace(' ','_') + '.zip'
 #如果目标目錄不存在就建立
 if not os.path.exists(today):
     os.mkdir(today)
     print ('Sucessfully created directoy',today)
 #備份指令,可替換為7z,linux下可改為tar等
 zip_command = "winrar a %s %s"%(target, ' '.join(source))
 #執行指令
 if os.system(zip_command) == 0:
     print('Successful backup to',target)
 else:
     print('Backup failed')
    注意:
    pycharm運作出現報錯資訊如下:
    "winrar" 不是内部或外部指令,也不是可運作的程式或批處理檔案。
    Backup failed
    解決方法:
    将winrar的安裝路徑,添加到環境變量path内即可。           

複制

轉貼:http://blog.51cto.com/y03113076/2087213