简体   繁体   English

为什么os.remove()或shutil.move()只能移动部分文件

[英]Why os.remove() or shutil.move() can only move part of files

I want to randomly choose 10 images from the training dataset to be the test data. 我想从训练数据集中随机选择10张图像作为测试数据。 If I only copy the selected data to the destination path, it works. 如果仅将所选数据复制到目标路径,则它可以工作。 But if I want to remove the source data, it can only remove some of them. 但是,如果我要删除源数据,则只能删除其中的一些。 I tried both os.remove() and shutil.move() function, but the issue remains. 我同时尝试了os.remove()和shutil.move()函数,但问题仍然存在。 The below is my script: 以下是我的脚本:

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')

And I add an image to show the running status. 我添加了一个图像以显示运行状态。

错误信息 You can see, the program indeed can copy the images and remove some of the images, but why it cannot remove all images? 您可以看到,该程序确实可以复制图像并删除某些图像,但是为什么它不能删除所有图像?

Any ideas? 有任何想法吗? I appreciate any helps! 感谢您的帮助!

In: 在:

ch1_mask = np.random.choice(len(ch1_imgs), 10)

You're potentially getting the same index returned more than once which means you're then trying to copy a file you've already copied and deleted (so you can't copy it again as it's removed), instead pass replace=False , eg: 您可能多次返回相同的索引,这意味着您要尝试复制已经复制和删除的文件(因此删除后就不能再复制),而是传递replace=False 。例如:

ch1_mask = np.random.choice(len(ch1_imgs), 10, replace=False)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM