簡體   English   中英

Python 將所有文件從多個子目錄移動到不同的對應子目錄

[英]Python move all files from multiple subdirectories to different corresponding subdirectories

我正在處理 python 腳本,將文件夾內子文件夾中的所有文件移至另一個具有相同結構子文件夾的文件夾。 (見圖)

圖片

我的腳本目前只是從目錄中獲取所有文件並移動到另一個文件夾位置。 有沒有一種優雅的方法可以做到這一點? 我正在處理一個文件夾中的 31 個子目錄,因此對所有 31 個子目錄進行硬編碼會很乏味

多謝

import shutil
import os
src = r'C:\folderA'
dst = r'C:\folderB'

for root, subdirs, files in os.walk(src):
    for file in files:
        path = os.path.join(root, file)
        shutil.move(path, dst)

您可以使用os.path.relpath獲取src的相對路徑,然后將該相對路徑與dst以獲得新的路徑名:

import shutil
import os
src = r'C:\folderA'
dst = r'C:\folderB'

for root, subdirs, files in os.walk(src):
    for file in files:
        path = os.path.join(root, file)
        shutil.move(path, os.path.join(dst, os.path.relpath(path, src)))

要處理多個目錄,可以構建{'src':'dest'}對的字典:

import shutil
import os
src_dst_map = {
   r'C:\folderA' : r'C:\folderB',
   r'C:\folderC' : r'C:\folderD'
} #ect

for src, dst in src_dst_map.items():
   for root, subdirs, files in os.walk(src):
      for file in files:
         path = os.path.join(root, file)
         shutil.move(path, dst)

首先,如果您想使用IIRC進行修改,可以調用copytree並傳遞move而不是copy2作為復印機,這樣最終會將所有文件移動到正確的位置,但可以在Unix或Windows上(我忘記了哪一個)它留下了空目錄而不是空目錄。 但這很簡單:

shutil.copytree(src, dst, function=shutil.move)
shutil.rmtree(src)

如果您不想要某些駭人聽聞的東西:

從您的圖中看來,您似乎只有31個子目錄都直接位於源目錄下,而不是相互嵌套。 因此,試圖用走整個層次遞歸walk ,然后試圖正確地重新組裝路徑等只是使事情變得更加復雜,甚至可能效率較低。

您所要做的就是獲取這31個目錄並進行move 例如,使用scandir

for entry in os.scandir(src):
    if entry.is_dir():
        shutil.move(entry.path, dst)

或者,如果您在頂層具有文件和目錄,則更加簡單:

for entry in os.scandir(src):
    shutil.move(entry.path, dst)

如果您使用的是沒有scandir的舊版本Python,則必須使用listdir ,但這僅稍微困難一點:

for name in os.listdir(src):
    shutil.move(os.path.join(src, name), dst)

這是進行重復檢查的修改方法:

src = r'D:\TestSourceFolder'
dst = r'D:\TestDestFolder'


for root, subdirs, files in os.walk(src):
    for file in files:
        path = os.path.join(root, file)
        
        print("Found a file: "+path)
        print("Only name of the file: "+file)
        print("Will be moved to: "+os.path.join(dst, file))
        
        # If there is no duplicate file present, then move else don't move
        if not os.path.exists(os.path.join(dst, file)):  
            #shutil.move(path, os.path.join(dst, os.path.relpath(path, src)))
            shutil.move(path, os.path.join(dst, file) )
            print("1 File moved : "+file+"\n")
        else:
            print("1 File not moved because duplicate file found at: "+path+"\n")

        

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM