Python shutil不将文件复制到指定文件夹

问题描述 投票:0回答:1

我正在尝试将文件从一个文件夹移动到同一目录中的另一个文件夹买我遇到问题。

这是我的代码到目前为止的样子:

current_dir = os.path.dirname(os.path.realpath(__file__))
folders = get_all_folders(current_dir)

os.mkdir('FINAL') # Final output stored here

for folder in folders:
    img_list = list(os.listdir(current_dir))

    for img in img_list:
        img_path = os.path.join(current_dir, img)

        final_folder = os.path.join(current_dir, 'FINAL')
        shutil.copyfile(img_path, final_folder)

FINAL文件夹是按预期创建的,但是将imgs复制到该文件夹​​的instad,在我循环的每个目录中创建一个名为FINAL的文件。

关于如何解决这个问题的任何想法?

python shutil
1个回答
0
投票

我认为你在这里犯的错误是你试图找到当前目录中的图像而不是当前目录中的文件夹。所以,当你打电话给shutil.copyfile()时,你最好根据你提供的代码得到一个IsADirectoryError。无论如何,我想这应该工作:

current_dir = os.path.dirname(os.path.realpath(__file__))

# Get all folder names in current directory before making the "FINAL" folder.
folders = get_all_folders(current_dir)

os.mkdir('FINAL') # Final output stored here

for folder in folders:
    folder_path = os.path.join(current_dir, folder)
    img_list = list(os.listdir(folder_path))

    for img in img_list:
        img_path = os.path.join(folder_path, img)

        final_folder = os.path.join(current_dir, 'FINAL')
        shutil.copyfile(img_path, final_folder)

此外,每次运行此脚本时都需要删除FINAL文件夹。最好在代码本身进行此类检查。

© www.soinside.com 2019 - 2024. All rights reserved.