繁体   English   中英

如何递归地将子目录中的所有文件移动到主文件夹? [Python]

[英]How to recursively move all files inside subdirectories to main folder? [python]

我有一个文件夹目录看起来有点像这样:

C:/Documents/A350/a/1.png
                   /2.png
                  b/1.png
            /B777/a/1.png
            /B747/a/1.png
                   /2.png
                  b/1.png
                  c/1.png
                  d/1.png
                   /2.png

我想将所有 png 移动到主文件夹,即 Documents。

def recur(input_path):
    dir_list = os.listdir(input_path)
    for directory in dir_list:
        path_name = os.path.join(input_path, directory)
        p = pathlib.Path(path_name)
        if p.is_dir():
            input_path = path_name
            return recur(input_path)
    return input_path

我有一些代码可以获取文件夹内的最深路径,但我不太确定如何使用递归 function 来实现我想要的。

任何帮助将不胜感激,谢谢!!

下面的程序从父目录递归获取所有文件并将文件复制到父目录。

import os
import glob
import shutil

files_abs_paths = []

def get_all_files(parent_dir):
    files_n_folders = glob.glob(f'{parent_dir}/**')
    
    for fl_or_fldr in files_n_folders:
        if os.path.isdir(fl_or_fldr):
            folder = fl_or_fldr
            get_all_files(folder)
        else:
            file = fl_or_fldr
            files_abs_paths.append(file)

parent_dir = r"C:'/Documents"

# get all files recursively in parent dir
get_all_files(parent_dir)

# copies files to parent_dir
for fl in files_abs_paths:
    # gets file_name
    file_name = os.path.basename(fl)

    # create file in parent_dir
    new_file_loc = f'{parent_dir}/{file_name}'
    if os.path.exists(new_file_loc) is False:
        shutil.copyfile(fl, new_file_loc)

您还可以使用os.walk从文件夹树中获取所有文件:

如果您不介意覆盖重名文件:

from os import walk, rename
from os.path import join

def collect_files(root):
    for src_path, _, files in walk(root):
        if src_path != root:
            for name in files:
                rename(join(src_path, name), join(root, name))

如果要在具有重名的文件末尾添加一个数字:

from os import walk, rename
from os.path import join, splitext, exists

def collect_files(root):
    for src_path, _, files in walk(root):
        if src_path != root:
            for name in files:
                dst_name = name
                dst_name_parts = splitext(dst_name)
                file_num = 1
                while exists(join(root, dst_name)):
                    dst_name = '{}_{:0>3}{}'.format(dst_name_parts[0], file_num, dst_name_parts[1])
                    file_num += 1
                rename(join(src_path, name), join(root, dst_name))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM