Linuxでは、変更されたファイルのみを構造全体で事前定義されたバックアップフォルダーにコピーするために、以下のバックアップスクリプトを準備しました。ファイルサイズまたは変更日のいずれかが変更された場合、「変更」を定義しました。active-stateを使用すると、Windowsでもこれを実装できます。
import os
import os.path
import sys
import time
from datetime import datetime
import shutil
backup_loc = '/media/prahlad/terabyte/backup'
locations = ['/home/prahlad/docs',
'/home/prahlad/source',
'/home/prahlad/scripts',
'/home/prahlad/library',
'/home/prahlad/programs',
'/home/prahlad/staging',
'/home/prahlad/soft',
'/home/prahlad/Desktop',
'/home/prahlad/Downloads',
'/home/prahlad/Pictures',
'/home/prahlad/videos',
'/home/prahlad/movies',
'/home/prahlad/songs',
]
if __name__ == "__main__":
#loop thru the folders
start = time.clock()
num=0
for s in locations: #[0:1]:
#print s + "\n"
#files = os.listdir(s)
print 'listing for ' + s
for (root, dirs, files) in os.walk(s):
#CON_LEN = 120
#print root, " contains"
#subpath = root[len(s)+1:]
subpath = root.replace('/home/prahlad','')
#~ for d in dirs:
#~ #create corresponding structure on backup if it doesn't exist
#~ print 'backup loc:',backup_loc
#~ print 'subpath:',subpath
#~ print 'd:',d
#~ print 's:',s
#~ #os.sepchar
#~ #destdir = os.path.join(backup_loc, subpath, d) #some how backup_loc is not being considered
#~ destdir = backup_loc + subpath + os.sep + d
#~ if not os.path.exists(destdir):
#~ print 'creating directory ' + destdir
#~ #print 'creating directory ' + destdir
#~ os.makedirs(destdir)
for f in files:
#print 'root: ' + root
#print 'file: ' + f
#print 'split: ' + root[len(s)+1:], len(root[len(s)+1:])
#message = os.path.join(root,f) + '~~~~' + os.path.join(backup_loc,subpath,f)
filename = os.path.join(root, f)
#dfilename = os.path.join(backup_loc,subpath,f)
dfilename = backup_loc + subpath + os.sep + f
link = ''
if os.path.islink(filename):
link = os.readlink(filename)
if not os.path.exists(dfilename):
#check dirs
if not os.path.exists(backup_loc + subpath):
os.makedirs(backup_loc + subpath)
print 'creating directory: ' + backup_loc + subpath
#just copy the files
print 'copying from: ' + filename
print 'to: ' + dfilename
if link == '':
shutil.copy2(filename, dfilename)
else:
os.symlink(link, dfilename)
num+=1
else:
sz = os.path.getsize(filename); lm = datetime.fromtimestamp(os.path.getmtime(filename)).timetuple()
dsz = os.path.getsize(dfilename); dlm = datetime.fromtimestamp(os.path.getmtime(dfilename)).timetuple()
if (sz == dsz and lm == dlm):
print 'skipped: ' + dfilename
#time.sleep(3)
else:
#copy the files
print 'copying from: ' + filename
print 'to: ' + dfilename
if link == '':
shutil.copy2(filename, dfilename)
else:
os.symlink(link, dfilename)
num+=1
mins = (time.clock() - start)
#print "All files copied in %d minutes" % mins
print "{0} files copied in {1} minutes".format(int(num), round(mins))