Python 簡単なファイルバックアップスクリプト

スクリプトのコード:

#! /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))

 

Development

Posted by arkgame