使用 Python 从多个文件夹中提取所有文件

sur*_*itt 1 python python-3.x

我写下了这段代码:

import shutil

files = os.listdir(path, path=None)
for d in os.listdir(path):
    for f in files:
        shutil.move(d+f, path)
Run Code Online (Sandbox Code Playgroud)

我希望给定目录 ( path)中的每个文件夹都包含文件,将该文件夹中包含的文件移动到包含该文件夹的主目录 ( path) 中。

例如:此文件夹中的文件: C:/example/subfolder/ 将被移入: C:/example/

(并且该目录将被删除。)对不起,我的英语不好:)

小智 5

这应该是您要查找的内容,首先我们在主文件夹中获取所有子文件夹。然后对于每个子文件夹,我们获取其中包含的文件并为shutil.move 创建我们的源路径和目标路径。

import os
import shutil

folder = r"<MAIN FOLDER>"
subfolders = [f.path for f in os.scandir(folder) if f.is_dir()]

for sub in subfolders:
    for f in os.listdir(sub):
        src = os.path.join(sub, f)
        dst = os.path.join(folder, f)
        shutil.move(src, dst)
Run Code Online (Sandbox Code Playgroud)