python 2 [Error 32] The process cannot access the file because it is being used by another process

白昼怎懂夜的黑 提交于 2020-01-05 07:19:07

问题


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,


回答1:


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



来源:https://stackoverflow.com/questions/40130958/python-2-error-32-the-process-cannot-access-the-file-because-it-is-being-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!