首页 > 解决方案 > 使用 np.random.choice() 选择要从 listdir() 结果移动的文件时出现“找不到文件”

问题描述

我正在尝试从包含图像的文件夹中采样 10k 个样本。以下是我使用的代码:

import numpy as np
import os
import shutil

ori_path = "D:\\LSUN\\lsun-master\\train_data_bedroom"
des_path = "D:\\LSUN\\lsun-master\\Train\\bedroom"
# list all files in dir
files = os.listdir(ori_path)

# select 10k of the files randomly 
random_files = np.random.choice(files, 10000)

#renaming index
ii = 1

for x in random_files:
    src = os.path.join(ori_path,x)
    des = os.path.join(des_path,str(ii)+".png")
    shutil.move(src,des)
    ii+=1

当我运行这段代码时,我总是在复制几张图像后得到这个错误

FileNotFoundError: [Errno 2] No such file or directory: 'D:\\LSUN\\lsun-master\\train_data_bedroom\\120c22c9525271d7041ed7883a23323cf53f67c8.png'

然后我回到我的源文件夹并搜索这个文件,我发现没有这样的文件。

所以我的问题是,listdir 如何找到文件夹中不存在的文件?我应该如何解决这个问题?

标签: python

解决方案


默认情况下,是一个带替换np.random.choice()的随机选择,这意味着可以选择两次相同的值(这个想法是一旦选择,它就会被放回从中随机选择项目的隐喻桶中)。

这意味着可以选择两次相同的文件,但是当然,一旦您移动了一个文件,它就不再存在,因此如果再次选择它,您的代码将失败。

通过replace=False关闭替换,因此每个文件只能选择一次:

random_files = np.random.choice(files, min(len(files), 10000), replace=False)

推荐阅读