I'm working with python 2 and have read several posts about this error i.e(this post).
However, I'm still getting the error.
What I do is:
I read the files in a directory, if any of the files contains a specific string, I delete the directory.
def select_poo():
path = os.walk('/paila_candonga/')
texto = 'poo'
extension = '.tex'
for root, dirs, files in path:
for documento in files:
if extension in documento:
with open(os.path.join(root, documento), 'r') as fin:
for lines in fin:
if texto in lines:
shutil.rmtree(root)
else:
continue
Then I get the error:
WindowsError: [Error 32] The process cannot access the file because it is being used by another process
I have also tried using the absolute path:
def select_poo():
path = os.walk('/paila_candonga/')
texto = 'poo'
extension = '.tex'
for root, dirs, files in path:
for documento in files:
if extension in documento:
with open(os.path.join(root, documento), 'r') as fin:
for lines in fin:
if texto in lines:
route = (os.path.join(root, documento))
files = os.path.basename(route)
folder = os.path.dirname(route)
absolut= os.path.dirname(os.path.abspath(route))
todo = os.path.join(absolut, files)
print todo
else:
continue
Then I will get:
C:\paila_candonga\la_Arepa.tex
C:\paila_candonga\sejodio\laOlla.tex
C:\paila_candonga\sejodio\laPaila.tex
If I remove one file at a time, using the same absolute path and os.remove(''), I won't have problems. If I try to delete all files at once using select_poo() and shutil.rmtree(folder) or os.remove(absolut), I will have the Error 32.
Is there a way I can do a loop through each of the paths in todo and remove them without having the error 32?
Thanks,
解决方案
it happens here :
with open(os.path.join(root, documento), 'r') as fin:
So you have your file open and locked, that is why you are not able delete this folder using:
shutil.rmtree(root)
within this statement, you have to do outside of with statement