I have a list that I am using to process a series of tasks on directories. Occasionally the process will get stuck at a certain directory. Currently I'm removing that element and re-running the process thru the list. However, this is getting to take a while.
Here's what I'm doing now:
directories = next(os.walk('/home'))[1]
directories.remove('brokendirectory')
process_directory(directory)
What I'd like to do is to remove EVERY directory INCLUDING the directory that's broken and only work on the list of directories after that broken directory. Something like this:
def clear_list(directories, element):
new_list = []
for directory in directories:
if directory == element:
break
else:
new_list.append(directory)
return(new_list)
directories = next(os.walk('/home'))[1]
new_directories = clear_list(directories,'brokendirectory')
process_directory(new_directories)
Obviously my function does not work as-is.
How can I remove all elements in the list including the one specified and return a new list for processing?
You can use index method of the the list to find the index of the element you want and then use a slice to remove all elements up to and including it.
directories = directories[directories.index('brokendirectory')+1:]
You can use the function dropwhile
:
from itertools import dropwhile
l = 'ABCDEFG'
element = 'D'
list(dropwhile(lambda x: x != element, l))
# ['D', 'E', 'F', 'G']
Find the index of the broken directory:
idx = directories.index('brokendirectory')
Use that index to slice a new list:
new_directories = directories[idx+1:]
Then process that:
process_directory(new_directories)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With