python 2[错误32]进程无法访问该文件,因为它正被另一个进程使用

2024-06-26 10:31:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python2并阅读了关于这个错误的几篇文章,即(this post)。 但是,我仍然得到错误。 我要做的是: 我读取目录中的文件,如果其中任何一个文件包含特定的字符串,我会删除该目录。在

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

然后我得到一个错误:

^{pr2}$

我也尝试过使用绝对路径:

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

如果我一次删除一个文件,使用相同的绝对路径和操作系统删除(''),我不会有问题的。如果我尝试使用select_poo()和舒蒂尔.rmtree(文件夹)或操作系统删除(绝对),我将得到错误32。在

有没有一种方法可以循环todo中的每个路径并删除它们而不会出现错误32?在

谢谢


Tags: pathinforifos错误extensionroot
1条回答
网友
1楼 · 发布于 2024-06-26 10:31:04

发生在这里:

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

因此,您已打开并锁定了文件,因此您无法使用以下方法删除此文件夹:

^{pr2}$

在此语句中,必须在with语句之外执行操作

相关问题 更多 >