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

标签 python windows python-2.7 loops shutil

我正在使用 python 2 并阅读了几篇关于此错误的文章,即(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

然后我得到错误:

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

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

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

谢谢,

最佳答案

它发生在这里:

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

所以您打开并锁定了文件,这就是为什么您无法使用以下方法删除此文件夹的原因:

shutil.rmtree(root)

在这个语句中,你必须在with语句之外做

关于python 2 [错误 32] 进程无法访问该文件,因为它正被另一个进程使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40130958/

相关文章:

python - Networkx 给出了错误的节点度数

c - 热补丁填充始终是 16 的倍数吗?

c++ - 为什么在 Linux 中编译的代码不能在 Windows 上运行?

python - 尝试使用shutil.move()将文件移动到子文件夹中

python - 为什么python 2.7.2在/usr/lib/python2.7中没有符号链接(symbolic link)

python - 没有类的属性方法

python - 使用 Python 在内存中提取多个压缩的 JSON 文件并将它们保存到 Azure Blob 存储

python celery - ImportError : No module named _curses - while attempting to run manage. py celeryev

javascript - Puppeteer 一次打开每个文件的 chrome 实例

python - Matplotlib 在方法和日期时间之间填充