python - 使用 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 如何找到文件夹中不存在的文件?我应该如何解决这个问题?
解决方案
默认情况下,是一个带替换np.random.choice()
的随机选择,这意味着可以选择两次相同的值(这个想法是一旦选择,它就会被放回从中随机选择项目的隐喻桶中)。
这意味着可以选择两次相同的文件,但是当然,一旦您移动了一个文件,它就不再存在,因此如果再次选择它,您的代码将失败。
通过replace=False
关闭替换,因此每个文件只能选择一次:
random_files = np.random.choice(files, min(len(files), 10000), replace=False)
推荐阅读
- javascript - window.open 打开一个弹出窗口而不是一个新窗口
- php - 我无法使用 Auth::attempt php laravel 登录
- sql - 在条件不匹配的地方显示 0
- flutter - flutter just_audio中音频标题之间的疑问
- python - 使用用户输入设置 Pygame 显示大小
- mysql - mysql join 性能慢
- android - 当连接未正确关闭时,为什么使用 WAL 模式的 SQLite 数据库中的数据会丢失?
- python-3.x - 从多个混合参数返回一个列表
- xml - 无法为 sampe_sore 加载核心:从 /opt/solr-8.8.0/server.solr/sample_core/conf/solrconfig.xml 加载配置时出错
- flask - 如何使用烧瓶将我的多部分表单数据请求转发到另一个 REST API