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

时间:2018-07-04 21:14:20

标签: python-3.x permissions python-3.6 shutil python-os

通常在此处提交代码时,我会尝试仅包含最少数量的代码来演示该问题。但是,直到编写代码的最后,我才遇到这个问题,这几乎使调试问题变得不可能。

我有一段代码可以在一些不同类型之间转换文件。该代码可以正常工作。它以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'

我完全不知道是什么导致了此错误,因此将不胜感激。

1 个答案:

答案 0 :(得分:2)

您已使用以下行将工作目录更改为您要删除的目录:

os.chdir('/')

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

在删除"C:/Users/Julian/Documents/conversion/conversion/secure"之前,只需将工作目录更改为根目录(class Button extends React.Component { render() { return ( <button style={{styles}}> {this.props.children} </button> ); } } Button = Radium(Button); const styles = { backgroundColor: red, ':hover': { backgroundColor: black } }; )。