Python deleting files

232 Views Asked by At

Im currently having a really hard time using for loops to delete files that have a hash match in my hash database.

I can successfully delete one image that has a match, but when deleting more, it tries to delete the image that it just deleted and then ends up crashing my program. I have no idea why it does this, any help would be very appreciated.

def checkImage():
database_file = "hash_database.txt"

for filename in os.listdir('NewImages//'):
    upload = file_path + '\\' + filename
    print(filename)

# Get hash of each image
for filename in os.listdir('NewImages//'):
    new_images = imagehash.phash(Image.open('NewImages//' + filename))

    with open(database_file) as checkingHash:
        if str(new_images) in checkingHash.read():
            print("Delete this image, hash is already in database")
            os.remove(upload)
        else:
            with open(database_file, "a") as databaseFileWrite:
                databaseFileWrite.write(str(new_images) + " " + filename + "\n")

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\Users\myalt\OneDrive\Desktop\Python Projects\Hashing\NewImages\image4.png'

EDIT:

after looking at it some more, I have found that its because my first for loop sets the file to delete to the last image in the directory. So the second for loop just keeps trying to delete the last image.

I know the issue now, I just don't know how to get around this.

0

There are 0 best solutions below