歡迎您光臨本站 註冊首頁

Python中整個文件夾的移動

←手機掃碼閱讀     火星人 @ 2014-03-12 , reply:0
  

最近做個項目是將一個目錄下整個文件夾移到另外一個目錄下。其中文件夾下又套了很多層文件夾,還有最難得一點是文件夾在不同的文件夾下如果有同名的文件夾,要移到同一個目錄下,又必須將同名的文件夾得所有內容整合在一起,例如:

目錄D盤下又如下內容:(D:/src/a  D:/src/b/a) 

目錄E盤:E:/dst

要將D:/src/a文件夾下的內容(含有文件夾和文件)、D:/src/b/a(含有的文件夾和文件)

(備註:文件夾下可能還有同名的)

移到E:/dst下

自己寫了一個函數可以實現以上功能:

Def  MoveDirAndFiles(srcPath,dstPath)

       allChangeFileList=os.listdir(srcPath)

       for changeFileItem in allChangeFileList:

              changeFilePath=os.path.join(srcPath,changeFileItem)

                     if os.path.isdir(changeFilePath):

                            dstAddPath=os.path.join.(dstPath,changeFileItem)

                                   if os.path.exits(dstAddPath):

                                          MoveDirAndFiles(changeFilePath,dstAddPath)

                                   Else:

                                          Shutil.copytree(changeFilePath,dstAddPath,False)

                                          Shutil.retree(changeFilePath)

                     Else:

                            Shutil.move(changeFilePath,dstPath)

       Os.rmdir(srcPath)

       Return Ture



[火星人 ] Python中整個文件夾的移動已經有377次圍觀

http://coctec.com/docs/program/show-post-71409.html