Simple Copy Files & Folders Script in Python

January 22, 2009
Tags: , , , ,

As I’ve mentioned before, I use Microsoft’s Windows Home Server as my home’s central data store. Recently, I upgraded from the trial to the full version. Since I was going to upgrade the installation, I figured that I might as well (slightly) upgrade the server itself. As such, I wanted to copy off the data from the hard drives before doing a format & reinstall of WHS. To do so, I accessed the “hidden” DE folder located on each of my WHS hard drives and copied the data to my local machine. When the data was transferred, I formatted the drive and re-added it to my new WHS install. However, when I started to transfer the data back, I noticed that many folders were scattered across multiple hard drives. Rather than manually merging the folders back together, I decided to write this simple Python script:

import os
import shutil
sourcePath = r'E:\120gb\data\DE\shares\Music'
destPath = 'Z:'
for root, dirs, files in os.walk(sourcePath):

    #figure out where we're going
    dest = destPath + root.replace(sourcePath, '')

    #if we're in a directory that doesn't exist in the destination folder
    #then create a new folder
    if not os.path.isdir(dest):
        os.mkdir(dest)
        print 'Directory created at: ' + dest

    #loop through all files in the directory
    for f in files:

        #compute current (old) & new file locations
        oldLoc = root + '\\' + f
        newLoc = dest + '\\' + f

        if not os.path.isfile(newLoc):
            try:
                shutil.copy2(oldLoc, newLoc)
                print 'File ' + f + ' copied.'
            except IOError:
                print 'file "' + f + '" already exists'

–Adam

3 Responses to “Simple Copy Files & Folders Script in Python”

  1. Apparently, newer versions of Windows handles the merging of files and folders automatically, so this script is completely unnecessary! Oh well…

  2. Hi .. I’m using your code to copy files from another PC on intranet to 1 PC. It looks pretty useful for me (thks for sharing your code) but except that it creates a file “khq.file” that doesn’t exist in my source file. when i want to recopy again it prompts the error. (I intend to backup the data from another PC). Is there a way to avoid for this?

    thks a lot for ya program

  3. Luthar,

    The script shouldn’t create any additional files. Perhaps “khq.file” exists in your source directory but is hidden in Windows Explorer? What is the exact error that you’re getting?

    –Adam

Leave a Reply