我正在使用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]该进程无法访问文件,因为该文件正在被另一个进程使用
发布评论