I am encountering an error that can probably be worked around but conceptually confusing to me and wondering if someone could shed some light.
When I recurse through directory structure calling shutil.rmtree() under certain condition, I get an error that amounts to an attempt to delete an already deleted object. Here is a simplest example:
def deleteFolder(path):
for obj in glob.glob(os.path.join(path, '*')):
print('obj name is ',obj)
if os.path.isdir(obj):
deleteFolder(obj)
print('removing path ',path)
print(os.listdir(path))
shutil.rmtree(path,False)
WindowsError Traceback (most recent call last)
<ipython-input-36-ad9561d5fc92> in <module>()
2 #path = 'C:\Users\Wes\Desktop\Test\Morphine\Album1'
3 #shutil.rmtree(path)
----> 4 deleteFolder('C:\Users\Wes\Desktop\Test\Level1')
<ipython-input-35-14a315bc6a80> in deleteFolder(path)
30 print('removing path ',path)
31 print(os.listdir(path))
---> 32 shutil.rmtree(path,False)
C:\Users\Wes\Anaconda2\lib\shutil.pyc in rmtree(path, ignore_errors, onerror)
250 os.remove(fullname)
251 except os.error, err:
--> 252 onerror(os.remove, fullname, sys.exc_info())
253 try:
254 os.rmdir(path)
C:\Users\Wes\Anaconda2\lib\shutil.pyc in rmtree(path, ignore_errors, onerror)
248 else:
249 try:
--> 250 os.remove(fullname)
251 except os.error, err:
252 onerror(os.remove, fullname, sys.exc_info())
WindowsError: [Error 2] The system cannot find the file specified: 'C:\\Users\\Wes\\Desktop\\Test\\Level1\\Level2'
Directory structure is /Level1/Level2/Level3 and fx is called w/ arg Level1. Obviously this is a stupid example, it is doing the recursion that shutil.rmtree is built for, but when you add a condition to whether or not to delete the directory it makes more sense.
Here is the print output:
('obj name is ', 'C:\\Users\\Wes\\Desktop\\Test\\Level1\\Level2')
('obj name is ', 'C:\\Users\\Wes\\Desktop\\Test\\Level1\\Level2\\Level3')
('removing path ', 'C:\\Users\\Wes\\Desktop\\Test\\Level1\\Level2\\Level3')
[]
('removing path ', 'C:\\Users\\Wes\\Desktop\\Test\\Level1\\Level2')
[]
('removing path ', 'C:\\Users\\Wes\\Desktop\\Test\\Level1')
['Level2']
So it seems to travel down to Level3, delete Level3, moves up to Level2, has no problem seeing that Level3 is no longer a subdir of Level2, deletes Level2, but then Level1 still see Level2 and errors. There seems to be some subtlety of scoping as it relates to os.path that I am missing.
Ultimately, I would like to go explore an entire tree starting at some root and prune directories which have no descendants that meet some certain criteria (contain audio files).