python對文件夾的一些操作

 

代碼片段(2)

[代碼] 複製文件夾

01 def CopyFolderOs(sFolder,tFolder):
02     sourcePath= sFolder
03     destPath= tFolder
04     forroot, dirs, files inos.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         ifnot os.path.isdir(dest):
12             os.mkdir(dest)
13             print'Directory created at: ' + dest
14   
15         #loop through all files in the directory
16         forf in files:
17   
18             #compute current (old) & new file locations
19             oldLoc= root + '\\' + f
20             newLoc= dest + '\\' + f
21   
22             ifnot os.path.isfile(newLoc):
23                 try:
24                     shutil.copy2(oldLoc, newLoc)
25                     print'File ' + f + ' copied.'
26                 exceptIOError:
27                     print'file "' +f + '" already exists'

[代碼] 刪除文件夾

1 def RemoveFolderOs(sourceDir,localAppDataPath):
2     forroot, dirs, files inos.walk(sourceDir):
3         forf in files:
4             os.unlink(os.path.join(root, f))
5         ford in dirs:
6             shutil.rmtree(os.path.join(root, d))
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章