如果文件夹的长度超过限制,请删除文件夹中的第一个文件


  • 首先我创建了一个文件夹,其中包含名为1.jpg到20.jpg的图像
  • 现在我想循环浏览这个文件夹,并将所有这些图像添加到列表/数组中
  • 我一直在检查这个数组/列表的长度,如果长度超过20,那么第一个图像文件应该被删除

我可以删除图像阵列的第一个元素,但我不知道如何删除文件夹路径中的实际图像

以下的代码

进口cv2

导入glob

将numpy导入为np

images=[19]

files=glob.glob("./output/*.jpg"(

对于文件中的x:

如果len(图像(>=19:image_array.pop((;

print("removed first element")
else:
image = cv2.imread(x)
image_array.append(images) #append each image to array
print("no issues")

print('images_array shape:',np.array(images(.shape(

cv2.imshow('frame',image_array[0](

cv2.waitKey(0(

我认为这会有所帮助:https://thispointer.com/python-how-to-remove-a-file-if-exists-and-handle-errors-os-remove-os-ulink/

import os
# Remove a file
os.remove('/home/somedir/Documents/python/logs')

在您的情况下:

files_list = ["/home/somedir/img1.jpg", "/home/somedir/img2.jpg", ...]
if len(files_list) > 20:
os.remove(files_list[0])
del files_list[0]

来自Grepper:os.remove("demofile.txt")

最新更新