Sunday, August 4, 2013

Tip Copying Files


#!/usr/bin/python

#copy all files from input path to current directory no overwriting is allowed, backup of current directory is not made
#
#@author Nathaniel Anozie
#
##

#@note inspired by Nicklas Puetz tutorials on python file querying operations nicklaspuetz dot blogspot dot com
#
##

#last updated: 08/04/2013 -- initial release


import getopt,sys

#for file stuff
import os

#for copy file stuff
import shutil

#for printing stuff
from pprint import pprint



#copy all files from input path to current directory no overwriting is allowed, backup of current directory is not made, no permissions checking is made
# 
def copyFile(d = '/tmp/test/t2/'):    

    destinationPath = os.path.abspath('.')  #current directory is destination path
    fromPath = d
       
    #hold all the file names that were copied
    result = []
    
    if os.path.isdir(d) and os.path.isdir(destinationPath):
        
        print 'Great Found Directories to Search >> %s ...\n' %d
        
        #things to copy cant already exist and must be files
        allFromFile = os.listdir(d)
        allFrom =  [os.path.join(d,f) for f in allFromFile]
        for fr in allFrom:
            print 'checking from file:%s\n' %fr
            if os.path.isfile(fr):
                #to check if file in a different directory first split file path and filename
                base, file = os.path.split(fr)
                toFilePath = os.path.join(destinationPath,file)
                if not os.path.exists(toFilePath):
                    print 'Copying File>> %s into >>%s' %(fr,toFilePath)
                    shutil.copyfile(fr,toFilePath)#copied files have same names as originals
                    result.append(toFilePath)
                    
    print 'Files Copied:\n'
    pprint(result)
    #for x in result:
    #    print '%s\n' %x

    
def usage():
    print "usage: copyFile [-d|--directory]"
    print "-d,--directory  path to copy files from"

def main():
    
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hd:", ["help","directory"])
    except getopt.GetoptError, err:
        #print help info and exit
        print str(err)
        usage()
        sys.exit(2)
    
    dir = '/tmp/test/t2/'   
    
    for o, a in opts:
        if o in ("-h","--help"):
            usage()
            sys.exit()
        elif o in ("-d","--directory"):
            dir = a
            
    copyFile(dir)
    
if __name__ == '__main__':
    print 'current _name is: '+__name__
    main()



cheers
-Nate