python 2 [Error 32] The process cannot access the file because it is being used by another process
<p>I'm working with python 2 and have read several posts about this error i.e(<a href="http://stackoverflow.com/questions/28396759/os-remove-in-windows-gives-error-32-being-used-by-another-process">this post</a>). 
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. </p>

<pre><code>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
</code></pre>

<p>Then I get the error:</p>

<pre><code>WindowsError: [Error 32] The process cannot access the file because it is being used by another process
</code></pre>

<p>I have also tried using the absolute path:  </p>

<pre><code>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
</code></pre>

<p>Then I will get: </p>

<pre><code>C:\paila_candonga\la_Arepa.tex
C:\paila_candonga\sejodio\laOlla.tex
C:\paila_candonga\sejodio\laPaila.tex
</code></pre>

<p>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. </p>

<p>Is there a way I can do a loop through each of the paths in todo and remove them without having the error 32?</p>

<p>Thanks,</p>

<p>it happens here :</p>

<pre><code>with open(os.path.join(root, documento), 'r') as fin:
</code></pre>

<p>So you have your file open and locked, that is why you are not able delete this folder using:</p>

<pre><code>shutil.rmtree(root)
</code></pre>

<p>within this statement, you have to do outside of <code>with</code> statement</p>

python windows python-2.7 loops shutil