I've created a list that contains file paths to files that I want to delete. What's the most Pythonic way to search through a folder, and it's sub folders for these files, then delete them?
Currently I'm looping through the list of file paths, then walking through a directory and comparing the files in the directory to the file that is in the list. There has to be a better way.
for x in features_to_delete:
name_checker = str(x) + '.jpg'
print 'this is name checker {}'.format(name_checker)
for root, dir2, files in os.walk(folder):
print 'This is the root directory at the moment:{} The following are files inside of it'.format(root)
for b in files:
if b.endswith('.jpg'):
local_folder = os.path.join(folder, root)
print 'Here is name of file {}'.format(b)
print 'Here is name of name checker {}'.format(name_checker)
if b == name_checker:
counter += 1
print '{} needs to be deleted..'.format(b)
#os.remove(os.path.join(local_folder, b))
print 'Removed {} \n'.format(os.path.join(day_folder, b))
else:
print 'This file can stay {} \n'.format(b)
else:
pass
So to clarify, what I'm doing now is looping through the entire list of features to delete, every iteration I'm also looping through every single file in the directory and all sub directories and comparing that file to the file that is currently looping in the features to delete list. It takes a very long time and seems like a terrible way to go about doing it.