python对文件夹的一些操作

来源:互联网 发布:淘宝地址武汉没有汉口 编辑:程序博客网 时间:2024/03/29 22:21
 

代码片段(2)

[代码] 复制文件夹

view source
print?
01def CopyFolderOs(sFolder,tFolder):
02    sourcePath=sFolder
03    destPath=tFolder
04    forroot, dirs, filesinos.walk(sourcePath):
05  
06        #figure out where we're going
07        dest=destPath + root.replace(sourcePath, '')
08  
09        #if we're in a directory that doesn't exist in the destination folder
10        #then create a new folder
11        ifnotos.path.isdir(dest):
12            os.mkdir(dest)
13            print'Directory created at: '+ dest
14  
15        #loop through all files in the directory
16        forfin files:
17  
18            #compute current (old) & new file locations
19            oldLoc=root + '\\' + f
20            newLoc=dest + '\\' + f
21  
22            ifnotos.path.isfile(newLoc):
23                try:
24                    shutil.copy2(oldLoc, newLoc)
25                    print'File '+ f +' copied.'
26                exceptIOError:
27                    print'file "'+f +'" already exists'

[代码] 删除文件夹

view source
print?
1def RemoveFolderOs(sourceDir,localAppDataPath):
2    forroot, dirs, filesinos.walk(sourceDir):
3        forfin files:
4            os.unlink(os.path.join(root, f))
5        fordin dirs:
6            shutil.rmtree(os.path.join(root, d))
 
http://www.oschina.net/code/snippet_72895_1576
原创粉丝点击