1. 程式人生 > 其它 >移動資料夾中子資料夾的所有檔案到指定路徑

移動資料夾中子資料夾的所有檔案到指定路徑

背景

我想移動某個資料夾中所有的子檔案到指定資料夾,如圖所示:

我需要把這裡所有的資料夾中的檔案移動到一個新的target_DIR資料夾中。

程式碼

# 把某個資料夾中所有子資料夾的檔案都移動到一個資料夾中
import shutil
import os
from tqdm import tqdm

#待移動檔案所屬資料夾
father_DIR="移動檔案所屬資料夾"+"\\"

#需要移動到的資料夾
target_DIR="需要移動到的資料夾"+"\\"

son_DIRs = os.listdir(father_DIR)
# 第二部分,將名稱為file的檔案複製到名為file_dir的資料夾中
for son_DIR in tqdm(son_DIRs):
    #子資料夾中的路徑
    son_DIR_path = os.path.join(father_DIR,son_DIR)
    son_DIR_path=son_DIR_path+"\\"
    #子資料夾中檔案的的路徑
    files = os.listdir(son_DIR_path)
    for file in tqdm(files):
        tif_file_path = son_DIR_path+ file
        target_file_path=target_DIR+file
        #將指定的檔案file移動到target_DIR的資料夾裡面
        shutil.move(tif_file_path,target_file_path)