- #! /usr/bin/env python
- # -*- coding: utf-8 -*-
- # backup.py
- ''' 通过先将需要备份的文件集中放入一个文件夹,
- 然后再压缩的方法实现简单的文档备份。
- '''
- import os
- import os.path
- import sys
- import shutil
- import time
- ### 数据部分 GEGIN
- cwd = '/home/danran'
- # 文件的路径都是以 cwd 作为当前工作目录的。
- config = ['.vimrc',
- '.xinitrc',
- '.config/Terminal/terminalrc',
- '/etc/fstab',
- '/etc/X11/xorg.conf']
- data = ['python',
- 'website',
- 'icons']
- all = config + data
- ### 数据部分 END
- def 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', source
- def 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://www.codesnippet.cn/detail/28112012705.html
来源: http://www.codesnippet.cn/detail/28112012705.html