Home > Software design >  Delete the first file in a folder if the length of a folder is more than the limit
Delete the first file in a folder if the length of a folder is more than the limit

Time:04-04

  • First I created a folder that contains Images named as 1.jpg till 20.jpg
  • Now I want to loop through this folder and add all these images into a list/array.
  • I keep checking the length of this array/list and if the length is more than say 20 then the first image file should be deleted

I am able to delete the first element of the array of Images but I am not knowing how to delete the actual Image in the path of the folder

CODE BELOW

import cv2

import glob

import numpy as np

images = [19]

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

for x in files:

if len(images) >= 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('image_array shape:', np.array(images).shape)

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

cv2.waitKey(0)

CodePudding user response:

I think this can be helpful: 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')

In your case:

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

CodePudding user response:

From Grepper: os.remove("demofile.txt")

  • Related