import os,sys maxfileload=1000000 blksize=1024*500
def copyfile(pathFrom,pathTo,maxfileload=maxfileload): """ :param pathFrom: :param pathTo: :param maxfileload: :return:
将单个文件逐字节从pathFrom复制到pathTo; 使用二进制文件模式阻止Unicode解码和换行"""if os.path.getsize(pathFrom)<=maxfileload: bytesFrom=open(pathFrom,'rb').read() open(pathTo,'wb').write(bytesFrom)else: fileFrom=open(pathFrom,'rb') fileTo=open(pathTo,'wb') while True: bytesFrom=fileFrom.read(blksize) if not bytesFrom:break fileTo.write(bytesFrom)
def copytree(dirFrom,dirTo,verbose=0): """ 将敌人From下的内容复制到dirTo,返回(文件和目录)数目形式的元组 为避免在某些平台上目录名不可解码,可能需要为其名使用字节 :param dirFrom: :param dirTo: :param verbose: :return: """
fcount=dcount=0for filename in os.listdir(dirFrom): pathFrom=os.path.join(dirFrom,filename) pathTo=os.path.join(dirTo,filename) if not os.path.isdir(pathFrom): try: if verbose>1:print('copying',pathFrom,'to',pathTo) copyfile(pathFrom,pathTo) fcount+=1 except: print('Error creating',pathTo,'--skipped') print(sys.exc_info()[0],sys.exc_info()[1]) else: if verbose:print('copying dir',pathFrom,'To',pathTo) try: os.mkdir(pathTo) below=copytree(pathFrom,pathTo) fcount+=below[0] dcount+=below[1] dcount +=1 except: print('Error creating', pathTo, '--skipped') print(sys.exc_info()[0], sys.exc_info()[1])return (fcount,dcount)
def getArgs(): """ 获取验证文件目录名参数 :return: """
try: dirFrom,dirTo=sys.argv[1:]except: print('Usage error:cpall.py dirFrom dirTo')else: if not os.path.isdir(dirFrom): print('ErrorLdirFrom is not a directory') elif not os.path.exists(dirTo): os.mkdir(dirTo) print('Note:dirTo was created') return (dirFrom,dirTo) else: print('Waring:dirTo already exist.') if hasattr(os.path,'samefile'): same=os.path.samefile(dirFrom,dirTo) else: same=os.path.abspath(dirFrom)==os.path.abspath(dirTo) if same: print('Error:dirFrom same as dirto') else: return (dirFrom,dirTo)
if name=='main': import time distuple=getArgs() if distuple: print('Copying...') start=time.clock() fcount,dcount=copytree(*distuple) print('Copied',fcount,'files',dcount,'directions',end=' ') print('in ',time.clock()-start,'seconds')
源代码在: