Stumbling Toward 'Awesomeness'

A Technical Art Blog

Sunday, October 26, 2008

Weekend Python Snippet- (Pt. 2)

So, before we looked at just outputting a list of the files that were on device1 and not device2, now I will copy the files to a folder on the main device.

The tricky thing about this is I want the directory structure intact. After looking as os.path, and pywin32, I didn’t see anything like ‘mkdir’ where it would make all the folders deep needed to recreate the branch that a file was in. I did however find a function online:

def mkdir(newdir):
    if os.path.isdir(newdir):
    elif os.path.isfile(newdir):
        raise OSError("a file with the same name as the desired " \
                      "dir, '%s', already exists." % newdir)
        head, tail = os.path.split(newdir)
        if head and not os.path.isdir(head):
        if tail:

To copy the files and create the directories, I altered the previous script a bit:

for (path, dirs, files) in os.walk(path2):
	for file in files:
		if os.path.basename(file) not in filenames:
			newPath = os.path.abspath(os.path.join(path,file)).replace(path2,(path1 + 'isItThere//'))
			fileFull = os.path.abspath(os.path.join(path,file))
			print fileFull + " not found in " + path1 + " file cloud"
			print "Copying " + fileFull + " >>> " + newPath
			if os.path.isdir(os.path.dirname(newPath)) == False:
			win32file.CopyFile (fileFull, newPath, 0))

The results printed should look like below, the files should have been copied accordingly and the directories created.

U:\photos\Crystal\Orlando - Lauras wedding\P0003270.jpg not found in D:\photos\Crystal\ file cloud
Copying U:\photos\Crystal\Orlando - Lauras wedding\P0003270.jpg >>> D:\photos\Crystal\isItThere\Orlando - Lauras wedding\P0003270.jpg
U:\photos\Crystal\Orlando - Lauras wedding\P0003271.jpg not found in D:\photos\Crystal\ file cloud
Copying U:\photos\Crystal\Orlando - Lauras wedding\P0003271.jpg >>> D:\photos\Crystal\isItThere\Orlando - Lauras wedding\P0003271.jpg
U:\photos\Crystal\Orlando - Lauras wedding\P0003272.jpg not found in D:\photos\Crystal\ file cloud

If I had time, or perhaps when I have time, I’ll add MD5 checks.

posted by Chris at 2:54 PM  

1 Comment »

  1. Hi! Just passing by, but I thought you’d be interested to know that the python ‘os’ module has a ‘makedirs’ function that creates a full directory tree if needed.
    Good luck at ILM 🙂

    Comment by rotoglup — 2008/11/20 @ 10:21 AM

RSS feed for comments on this post. TrackBack URI

Leave a comment

Powered by WordPress