【问题标题】:Python's shutil Not copying Files to Specified FolderPython的shutil不将文件复制到指定文件夹
【发布时间】:2018-09-09 17:27:33
【问题描述】:

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

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

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 复制到该文件夹​​之外,在我循环访问的每个目录中都会创建一个名为 FINAL 的文件。

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

【问题讨论】:

    标签: python shutil


    【解决方案1】:

    我认为您在这里犯的错误是您试图在当前目录中而不是当前目录中的文件夹中查找图像。因此,当您拨打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 文件夹。最好在代码本身中进行此类检查。

    【讨论】:

      猜你喜欢
      • 2016-03-15
      • 1970-01-01
      • 2023-01-29
      • 2018-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-20
      相关资源
      最近更新 更多