使用Python递归地将子目录中的所有文件移动到另一个目录

3
标题已经解释了我的需求。请注意,子目录中不会包含任何目录,只有文件(*.JPG)。基本上,只是将文件树中的所有内容向上移动一个级别。
例如,从~/someDir/folder1/*~/someDir/folder2/*,...,~/someDir/folderN/*。我希望将所有子目录的内容都移到~/someDir/下。
4个回答

7

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)。这将仅复制所有文件,如果需要,您可以手动清理源目录。


0

如果文件名相同,可以使用此选项,新文件名将由文件夹名称以“_”连接而成

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)

0

此外,您也可以使用 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'))

0
这是一种修改后的方法,并带有重复检查:
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")

        

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接