[英]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.