备份文件夹python脚本

  出于备份网站内容的考虑,故花了点时间写了个能够备份文件夹的 Python 小脚本,用于把自己写的博文目录备份为zip并放到指定目录。功能很简单,代码量也很少。

#!/usr/bin/python
# -*- coding: UTF-8 -*- 
'''
A tool using to backup directory.
Author:Victor Lv
Date: 2017-8-19
'''

import os, sys, time, shutil

# You can modify the source path and destination path,
# all the files / directories in srcPath\\ will be zip to desPath\\%DATE%.zip
SRC_PATH = "D:\\mysite\\Hexo"
DES_PATH = "D:\\mysite\\backup\\"

CURRENT_TIME = time.strftime("%Y-%m-%d_%H-%M",time.localtime())
ZIP_NAME = DES_PATH + CURRENT_TIME + "_backup"


def error_throw(error_message):
    print error_message
    sys.exit(1)


def check_src_path():
    if not os.path.exists(SRC_PATH):
        print(SRC_PATH)
        error_throw("Source path does not exist.")
    #elif not os.path.isdir(SRC_PATH):
    #    error_throw("Source path isn't a directory.")
    else:
        pass


def check_des_path():
    if not os.path.exists(DES_PATH):
        print("""Destination path does not exist.
Automatically create the directory...""")
        os.mkdir(DES_PATH)
    elif not os.path.isdir(DES_PATH):
        error_throw("Destination path isn't a directory.")
    else:
        pass


def copy_dir():
    shutil.make_archive(ZIP_NAME, 'zip', SRC_PATH)


def check_result():
    if os.path.exists(ZIP_NAME+'.zip'):
        print("Backup success.")
    else:
        error_throw("Backup failed.")


def main():
    check_src_path()
    check_des_path()
    copy_dir()
    check_result()
    sys.exit(0)


if __name__ == '__main__':
    main()

  这里面用到了几个关键模块:

time.strftime 模块

  用于获取当前时间,参考教程:
  How to get current time in Python ? stackoverflow

shutil.make_archive 模块

  用于打包成zip文件,参考教程:
  How to create a zip archive of a directory ? stackoverflow

最后效果如下:
演示效果图

标签: Python

添加新评论