2016-10-19 263 views
0

我正在使用python 2并已阅读关于此错误的多个帖子,即(this post)。 但是,我仍然收到错误。 我所做的是: 我读取目录中的文件,如果任何文件包含特定的字符串,我删除该目录。python 2 [错误32]进程无法访问该文件,因为它正在被另一个进程使用

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 

我已经使用绝对路径也试过:

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 

如果我一次删除一个文件,使用相同的绝对路径d os.remove(''),我不会有问题。如果我尝试使用select_poo()和shutil.rmtree(文件夹)或os.remove(绝对)一次性删除所有文件,我将会出现错误32.

是否有办法通过每个循环在todo中的路径,并删除它们没有错误32?

感谢,

回答

1

它发生在这里:

with open(os.path.join(root, documento), 'r') as fin: 

所以,你有你的文件打开并锁定,这就是为什么你使用无法删除此文件夹:

shutil.rmtree(root) 

内此声明,您必须在with声明外面做

+0

感谢Alex,但它不会工作。该错误仍然存​​在=( –

+0

@Chüngel你确定你没有这个文件夹或任何其他应用程序中打开此文件夹中的任何文件? – Alex

+0

亚历克斯,我很新的Python,但如果我删除使用操作系统的文件.remove(绝对)相同的文件将被删除而没有错误。所以我相信这个错误是由我在同一时间删除所有文件的过程所引起的。正如你所建议的,我定义了一个变量x = [],然后if在文档中找到字符串,路径将被附加到x,然后在with语句之外,我执行os.remove(x [0]),但是我得到了完全相同的错误。我的代码基于你的想法? –

相关问题