Python 檔案和資料夾的操作 shutil 模組
阿新 • • 發佈:2018-12-18
Python shutil模組
shutil模組操作 移動、改名和刪除檔案和資料夾
複製檔案
import shutil import os optSrcPath = "C:\\Users\\Administrator\\Desktop\\opt"#測試檔案目錄 # optDesPath = "C:\\Users\\Administrator\\Desktop\\opt\\test"#測試目標目錄 optDesPath = os.path.join(optSrcPath,"test")#測試目標目錄 fileName = "test.txt"#測試目標檔案 shutil.copy(os.path.join(optSrcPath,fileName),os.path.join(optDesPath,fileName))#複製檔案 目標路徑必須存在 如果目標目錄有同名的檔案會覆蓋
複製資料夾
import shutil
optSrcPath = "C:\\Users\\Administrator\\Desktop\\opt\\test"#測試目標目錄
optDesPath = "C:\\Users\\Administrator\\Desktop\\test"#測試檔案目錄
# The destination directory must not already exist.
newPath = shutil.copytree(optSrcPath,optDesPath)#返回
移動檔案
import shutil import os optSrcPath = "C:\\Users\\Administrator\\Desktop\\opt"#測試檔案目錄 # optDesPath = "C:\\Users\\Administrator\\Desktop\\opt\\test"#測試目標目錄 optDesPath = os.path.join(optSrcPath,"test")#測試目標目錄 fileName = "test.txt"#測試目標檔案 shutil.move(os.path.join(optSrcPath,fileName),optDesPath)#複製檔案 目標路徑必須存在 並且不能存在同名檔案
移動資料夾
import shutil
optSrcPath = "C:\\Users\\Administrator\\Desktop\\opt\\test"#測試目標目錄
optDesPath = "C:\\Users\\Administrator\\Desktop\\test"#測試檔案目錄
newPath = shutil.move(optSrcPath,optDesPath)#返回
刪除資料夾
import shutil optSrcPath = "C:\\Users\\Administrator\\Desktop\\opt\\test"#測試目標目錄 optDesPath = "C:\\Users\\Administrator\\Desktop\\test"#測試檔案目錄 shutil.rmtree(optDesPath)#返回 shutil.rmtree(optSrcPath)#被刪除資料夾必須存在