使用 shutil 将图像移动到新文件夹最终会用我正在移动的文件替换这个文件夹

乘风 pytorch 199

原文标题Moving images to a new folder with shutil ends up in replacing this folder with the files I was moving

我想将train目录中的一张狗和猫的图像移动到两个目录train/dogstrain/cats以准备使用 PyTorch 的 ImageFolder 功能。然而,当没有/在新目录的末尾完成时,似乎不是将文件移动到新的 train/dogs 文件夹,而是将图像移动到 train/dogs 文件

# we move dogs to train/dogs and cats to train/cats
import re

train_dir = "train"
train_dogs_dir = f'{train_dir}/dogs'
train_cats_dir = f'{train_dir}/cats'

files = os.listdir(train_dir)

for f in files: 
    catSearchObj = re.search("cat", f)
    dogSearchObj = re.search("dog", f)
    if catSearchObj:
        shutil.move(f'{train_dir}/{f}', train_cats_dir)
    elif dogSearchObj:
        shutil.move(f'{train_dir}/{f}', train_dogs_dir)

确实,在那之后他做到了! the train/dogs回答我:

train/dogs

! cat train/dogs

����JFIF��C



#%$""!&+7/&)4)!"0A149;>>>%.DIC<H7=>;��C
;("(;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;��w�"��   
���}!1AQa"q2��#B��R��$3br�  
%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz���������������������������������������������������������������������������    

原文链接:https://stackoverflow.com//questions/71516192/moving-images-to-a-new-folder-with-shutil-ends-up-in-replacing-this-folder-with

回复

我来回复
  • jgreve的头像
    jgreve 评论

    shutil文档为move()说“如果目标是一个现有目录,那么 src 将移动到该目录内。”(强调添加)

    您的目标目录可能不存在吗?

    如果这些目录不存在,您可能需要创建它们。

    2年前 0条评论