1、拷贝文件夹
fromshutilimportcopytree,ignore_patterns copytree(source,destination,ignore=ignore_patterns('*.pyc','tmp*'))
注:shutil.copytree实现
defcopytree(src,dst,symlinks=False,ignore=None): names=os.listdir(src) ifignoreisnotNone: ignored_names=ignore(src,names) else: ignored_names=set() os.makedirs(dst) errors=[] fornameinnames: ifnameinignored_names: continue srcname=os.path.join(src,name) dstname=os.path.join(dst,name) try: ifsymlinksandos.path.islink(srcname): linkto=os.readlink(srcname) os.symlink(linkto,dstname) elifos.path.isdir(srcname): copytree(srcname,dstname,symlinks,ignore) else: copy2(srcname,dstname) #XXXWhataboutdevices,socketsetc.? except(IOError,os.error)aswhy: errors.append((srcname,dstname,str(why))) #catchtheErrorfromtherecursivecopytreesothatwecan #continuewithotherfiles exceptErroraserr: errors.extend(err.args[0]) try: copystat(src,dst) exceptWindowsError: #can'tcopyfileaccesstimesonWindows pass exceptOSErroraswhy: errors.extend((src,dst,str(why))) iferrors: raiseError(errors)
2、删除文件夹
#!/usr/bash/python #encoding:utf-8 importos importos.path importstat importshutil classDelDir: '''删除指定根目录下特定文件夹''' def__init__(self,root,dirname): self.root=root self.dirname=dirname defrun(self): forr,dirs,filesinos.walk(self.root): ifself.dirnameindirs: srcDir=os.path.join(r,self.dirname) #更改权限(win7会出现权限问题) os.chmod(srcDir,stat.S_IREAD|stat.S_IWRITE) result=shutil.rmtree(srcDir,False,self.__handler) print"%s"%(srcDir) def__handler(self,function,path,excinfo): '''删除出错处理''' #更改权限(win7会出现权限问题) os.chmod(path,stat.S_IREAD|stat.S_IWRITE) function(path) print"[Handler]==>Path:%s\n\tHandlertheError:%s"%(path,excinfo) if__name__=='__main__': rootdir=r"E:\workspace\minioffice\mini-core\src\main\webapp"#需要处理的文件夹 rootdir=unicode(rootdir,"utf8") dirname=".svn"#删除的文件夹 c=DelDir(rootdir,dirname) c.run()原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容