Python3: 文件正在被另一个进程使用

Python3: File is being used by another process

通常在此处提交代码时,我会尽量只包含最少量的代码来演示问题。但是,直到写代码的最后才遇到这个问题,导致几乎无法调试问题。

我有一段代码可以在一些不同类型之间转换文件。该代码可以正常运行,没有任何问题。它以 ZIP 文件中的 XCI 文件开头,并将其转换为文件夹。但是,在代码的最后,我试图让我的脚本删除它创建的一些临时文件夹。这会导致我无法成功解决的有点令人困惑的错误。

import os, shutil, zipfile
from shutil import copyfile
from time import sleep

for fileName in os.listdir("D:/start"):
    filePath = "D:/start" + fileName 
    os.makedirs("C:/Users/Julian/Documents/conversion/extract")

    copyfile(filePath, "C:/Users/Julian/Documents/conversion/extract/game.zip")

    print("Extracting C:/Users/Julian/Documents/conversion/extract/game.zip")
    zip_ref = zipfile.ZipFile("C:/Users/Julian/Documents/conversion/extract/game.zip", 'r')
    zip_ref.extractall("C:/Users/Julian/Documents/conversion/extract")
    zip_ref.close()

    for file in os.listdir("C:/Users/Julian/Documents/conversion/extract"):
        if file.endswith(".xci"):
            os.rename(os.path.join("C:/Users/Julian/Documents/conversion/extract", file), "C:/Users/Julian/Documents/conversionh/extract/game.xci")

    os.system("C:/Users/Julian/Documents/conversion/hactool/hactool.exe -t xci C:/Users/Julian/Documents/conversion/extract/game.xci --outdir=C:/Users/Julian/Documents/conversionh/extract")

    fileSizeTupleList = []
    largestSize = 0

    os.chdir("C:/Users/Julian/Documents/conversion/conversion/secure")
    for i in os.listdir(os.curdir):
        if os.path.isfile(i):
            fileSizeTupleList.append((i, os.path.getsize(i)))

    for fileName, fileSize in fileSizeTupleList:
        if fileSize > largestSize:
            largestSize = fileSize
            largestFile = fileName

    print("Extracting C:/Users/Julian/Documents/conversion/extract/secure/" + largestFile)

    os.system("C:/Users/Julian/Documents/conversion/hactool/hactool.exe -t nca -k C:/Users/Julian/Documents/conversion/hactool/keys C:/Users/Julian/Documents/conversion/extract/secure/" + largestFile + " --exefsdir=C:/Users/Julian/Documents/conversion/game --romfs=C:/Users/Julian/Documents/conversion/game/RomFS.romfs")
    shutil.copytree("C:/Users/Julian/Documents/conversion/game", "D:/end/" + os.path.split(filePath)[1][:-4])
    shutil.rmtree("C:/Users/Julian/Documents/conversion/extract")
    shutil.rmtree("C:/Users/Julian/Documents/conversion/game")

此代码在到达倒数第二行之前工作正常。那时,我遇到了以下错误:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/Users/Julian/Documents/conversion/extract\secure'

我完全不知道是什么导致了这个错误,所以任何帮助将不胜感激。

您已将工作目录更改为您尝试使用此行删除的目录:

os.chdir("C:/Users/Julian/Documents/conversion/conversion/secure")

因此您无法删除该目录,因为您的 python 脚本进程正在使用它。

在删除 "C:/Users/Julian/Documents/conversion/conversion/secure".

之前,只需将您的工作目录更改为根目录 (os.chdir('/'))