“找不到文件”使用np.random.choice()时,选择文件从listdir同时移动()结果

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

我试图从包含图像的文件夹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
1个回答
0
投票

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

这意味着,一旦你移动的文件相同的文件可以选择两次,但当然,它不存在任何时间更长,所以如果它再次选择你的代码将失败。

通过replace=False关闭更换,因此每个文件都可以一次选择:

random_files = np.random.choice(files, min(len(files), 10000), replace=False)
© www.soinside.com 2019 - 2024. All rights reserved.