Python 简单的备份文件脚本,python备份脚本,#! /usr/bin/
文章由Byrx.net分享于2019-03-23 09:03:37
Python 简单的备份文件脚本,python备份脚本,#! /usr/bin/
#! /usr/bin/env python# -*- coding: utf-8 -*-# backup.py''' 通过先将需要备份的文件集中放入一个文件夹, 然后再压缩的方法实现简单的文档备份。'''import osimport os.pathimport sysimport shutilimport time### 数据部分 GEGINcwd = '/home/danran'# 文件的路径都是以 cwd 作为当前工作目录的。config = ['.vimrc', '.xinitrc', '.config/Terminal/terminalrc', '/etc/fstab', '/etc/X11/xorg.conf']data = ['python', 'website', 'icons']all = config + data### 数据部分 ENDdef copy_file(source, target_dir): '对比文件,如果目标文件不存在或者还是源文件新,则拷贝或覆盖文件。' # 如果路径有前缀 '/',则先将其去除。 target = os.path.join(target_dir, source[:1] == '/' and source[1:] or source) if not os.path.exists(target): dir, name = os.path.split(target) if not os.path.exists(dir): os.makedirs(dir) shutil.copy(source, target) print 'Backup', source elif os.path.getmtime(source) > os.path.getmtime(target): shutil.copy(source, target) print 'Backup', sourcedef copy_dir(top, target_dir): '递归地利用 copy_file 函数进行文件夹的拷贝。' for root, dirs, files in os.walk(top): for file in files: filepath = os.path.join(root, file) copy_file(filepath, target_dir)if __name__ == '__main__': if (len(sys.argv) == 2 and sys.argv[1] != '-m') or len(sys.argv) > 2: print '''Usage: backup.py [-m] 加入 -m 参数则将 tar 文件移动到 winE 分区中。''' sys.exit(1) # 临时存放需要备份的文件,便于打包。 tmp_dir = 'backup' # 最终备份文件的保存路径。 bkpath = '/mnt/winE/linux/backup' date = time.strftime('%y-%m-%d') os.chdir(cwd) for source in all: if os.path.isfile(source): copy_file(source, tmp_dir) else: copy_dir(source, tmp_dir) os.system('tar -czf %s.tar.gz %s' % (date, tmp_dir)) if len(sys.argv) == 2 and sys.argv[1] == '-m': os.system('mv %s.tar.gz %s' % (date, bkpath))#该片段来自于http://byrx.net
评论关闭