Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Small script to copy the difference between two folders to a new folder
#!/usr/bin/env python
import os
import os.path
import sys
import shutil
# Bugfixed version of makedirs
def makedirs(name, mode=0777):
"""makedirs(path [, mode=0777])
Super-mkdir; create a leaf directory and all intermediate ones.
Works like mkdir, except that any intermediate path segment (not
just the rightmost) will be created if it does not exist. This is
head, tail = os.path.split(name)
if not tail:
head, tail = os.path.split(head)
if head and tail and not os.path.exists(head):
makedirs(head, mode)
except OSError, e:
# be happy if someone already created the path
if e.errno != errno.EEXIST:
if tail == curdir: # xxx/newdir/. exists if xxx/newdir exists
# Bugfix: Don't fail if directory exists
if not os.path.exists(name):
os.mkdir(name, mode)
os.makedirs = makedirs
class DiffFolders:
def run(self, args):
src1 = os.path.abspath( args[0] )
src2 = os.path.abspath( args[1] )
dest = os.path.abspath( args[2] )
if not os.path.exists(src1):
raise Exception('Missing source folder %s' % src1)
if not os.path.exists(src2):
raise Exception('Missing source folder %s' % src2)
if os.path.exists(dest):
print 'Deleting %s' % dest
def ignore(folder, content):
if folder.startswith(src1):
prefix = src2
relpath = os.path.relpath(folder, src1)
prefix = src1
relpath = os.path.relpath(folder, src2)
result = []
for entry in content:
path = os.path.join(folder, entry)
if os.path.isdir(path):
if not os.path.isfile(path):
raise Exception('Can only handle files: %s' % path)
otherPath = os.path.join(prefix, relpath, entry)
if os.path.exists(otherPath):
if not os.path.isfile(otherPath):
raise Exception('Expected two files:\n%s\n%s' % (path, otherPath))
result.append( entry )
return result
shutil.copytree(src1, dest, ignore=ignore)
shutil.copytree(src2, dest, ignore=ignore)
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment