[英]Why os.remove() or shutil.move() can only move part of files
我想从训练数据集中随机选择10张图像作为测试数据。 如果仅将所选数据复制到目标路径,则它可以工作。 但是,如果我要删除源数据,则只能删除其中的一些。 我同时尝试了os.remove()和shutil.move()函数,但问题仍然存在。 以下是我的脚本:
for label in labels:
training_data_path_ch1 = os.path.join(training_data_folder, label, 'ch1')
test_data_path_ch1 = os.path.join(test_data_folder, label, 'ch1')
training_data_path_ch5 = os.path.join(training_data_folder, label, 'ch5')
test_data_path_ch5 = os.path.join(test_data_folder, label, 'ch5')
ch1_imgs = listdir(training_data_path_ch1)
# Randomly select 10 images
ch1_mask = np.random.choice(len(ch1_imgs), 10)
ch1_selected_imgs = [ch1_imgs[i] for i in ch1_mask]
for selected_img in ch1_selected_imgs:
ch1_img_path = os.path.join(training_data_path_ch1, selected_img)
shutil.copy2(ch1_img_path, test_data_path_ch1)
os.remove(ch1_img_path)
print('Successfully move ' + label + ' ch1 images')
我添加了一个图像以显示运行状态。
您可以看到,该程序确实可以复制图像并删除某些图像,但是为什么它不能删除所有图像?
有任何想法吗? 感谢您的帮助!
在:
ch1_mask = np.random.choice(len(ch1_imgs), 10)
您可能多次返回相同的索引,这意味着您要尝试复制已经复制和删除的文件(因此删除后就不能再复制),而是传递replace=False
。例如:
ch1_mask = np.random.choice(len(ch1_imgs), 10, replace=False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.