python 2 [错误32]该进程无法访问文件,因为该文件正在被另一个进程使用 [英] python 2 [Error 32] The process cannot access the file because it is being used by another process
问题描述
我正在使用python 2,并阅读了有关此错误的几篇文章,即(
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
然后我得到了错误:
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
然后我会得到:
C:\paila_candonga\la_Arepa.tex
C:\paila_candonga\sejodio\laOlla.tex
C:\paila_candonga\sejodio\laPaila.tex
如果使用相同的绝对路径和os.remove('')一次删除一个文件,则不会有问题.如果我尝试使用select_poo()和shutil.rmtree(folder)或os.remove(absolut)一次删除所有文件,则将出现错误32.
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.
有没有一种方法可以遍历待办事项中的每个路径并删除它们而不会出现错误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?
谢谢
推荐答案
它在这里发生:
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)
在此语句内,您必须在with
语句外
within this statement, you have to do outside of with
statement
这篇关于python 2 [错误32]该进程无法访问文件,因为该文件正在被另一个进程使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!