使用np.random.choice()选择要从listdir()移动的文件时出现“找不到文件”

2024-05-19 14:44:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从一个包含图像的文件夹中采集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如何找到文件夹中不存在的文件?我该怎么解决这个问题


Tags: 文件path图像importmaster文件夹osrandom
1条回答
网友
1楼 · 发布于 2024-05-19 14:44:14

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

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

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

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

相关问题 更多 >