用Python备份文件夹的小脚本

Title: 备份文件夹Python脚本
Category: 技术博客
Date: 2017-8-19 22:10
Modified: 2017-8-19 22:10
Tags: python
Slug: backup-directories-python
Authors: Victor Lv
Summary: 出于备份网站内容的考虑,故花了点时间写了个能够备份文件夹的 Python 小脚本,用于把自己写的博文目录备份为zip并放到指定目录。功能很简单,代码量也很少

  出于备份网站内容的考虑,故花了点时间写了个能够备份文件夹的 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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值