Here is my code:
# search for a file, and show all files found in that file's directory
# delete them if wanted
import os
import pickle
def file_find(folder):
"""search for a filename fname starting in folder"""
for root, dirs, files in os.walk(folder):
for file in files:
# make search case insensitive
if fname.lower() == file.lower():
return os.path.join(root)
return None
# file to search for ...
fname = raw_input("File? ")
# folder to start search ...
folder = raw_input("Directory? ")
result = file_find(folder)
if result:
print "File found -->", result
print "\n===============================\nFollowing are the files in the same directory\n===============================\n"
directory = result
allfiles = [] #store all files found
for root,dir,files in os.walk(directory):
filelist = [ os.path.join(root,fi) for fi in files ]
for f in filelist:
allfiles.append(f)
fileAmount = len(allfiles)
for i in allfiles:
print "file ", i
print "\n===============================\n"
counter = 0
while counter != fileAmount:
showFile = allfiles[counter]
counter += 1
if counter == fileAmount:
break
deleteFiles = raw_input("Delete whole list? (y/n): ")
if deleteFiles == "Y" or deleteFiles == "y":
print "Sure?"
positive = raw_input("To delete, type: 'delete', to not delete, type anything else... ")
if positive == "delete" or positive == "Delete":
counter = 0
while counter != fileAmount:
hostageFile = allfiles[counter]
os.remove(hostageFile)
counter += 1
print "deleted",counter,"files..."
if counter == fileAmount:
break
raw_input("")
else:
print "NO files deleted..."
raw_input("")
else:
print "NO files deleted..."
raw_input("")
else:
print "File %s not found" % fname
raw_input("")
But when it is trying to delete a directory with files that wont be easily deleted, it errors and closes.
I would like to add to the code a way to tell it to skip files that don't want to be deleted, and continue deleteing other files.