簡體   English   中英

Python遞歸移動子目錄下的所有文件到另一個目錄

[英]Recursively move all files on subdirectories to another directory in Python

標題解釋了我所追求的。 請注意,子目錄不會包含任何目錄文件(*.JPG)。 本質上,只是將文件樹中的所有內容向上移動一個級別。

例如,來自~/someDir/folder1/* , ~/someDir/folder2/* , ... , ~/someDir/folderN/* 我想要將子目錄的所有內容帶到~/someDir/

shutil.move 是移動文件的好選擇。

import shutil
import os

source = "/parent/subdir"
destination = "/parent/"
files_list = os.listdir(source)
for files in files_list:
    shutil.move(files, destination)

對於遞歸移動,您可以嘗試shutil.copytree(SOURCE, DESTINATION) 它只是復制所有文件,如果需要,您可以手動清理源目錄。

使用shutil模塊。

官方文件:

https://docs.python.org/3/library/shutil.html#module-shutil

此外,您可以使用Pathlib實現類似的功能。

from pathlib import Path
def _move_all_subfolder_files_to_main_folder(folder_path: Path):
    """
    This function will move all files in all subdirectories to the folder_path dir.
    folder_path/
        1/
            file1.jpg
            file2.jpg
        2/ 
            file4.jpg
    outputs:
    folder_path/
        file1.jpg
        file2.jpg
        file4.jpg
    """
    if not folder_path.is_dir():
        return

    for subfolder in folder_path.iterdir():
        for file in subfolder.iterdir():
            file.rename(folder_path / file.name)

用法是:

_move_all_subfolder_files_to_main_folder(Path('my_path_to_main_folder'))

使用這個,如果文件具有相同的名稱,新名稱將具有由 '_' 連接的文件夾名稱

import shutil
import os

source = 'path to folder'

def recursive_copy(path):

    for f in sorted(os.listdir(os.path.join(os.getcwd(), path))):

        file = os.path.join(path, f)

        if os.path.isfile(file):

            temp = os.path.split(path)
            f_name = '_'.join(temp)
            file_name = f_name + '_' + f
            shutil.move(file, file_name)

        else:

            recursive_copy(file)
         
recursive_copy(source)

這是修改后的方法以及重復檢查:

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