3

我正在编写一些代码,根据文件的标题向文件添加扩展名。使用任何 gzip 文件,我都在提取数据。

当我尝试运行代码时,我得到一个 WinError 32。下面是代码和错误

感谢您的任何建议。

def extract():
    os.chdir("C:/Users/David/MyFiles")
    files = os.listdir(".")
    for x in (files):
        inputFile = open((x), "rb")
        byte1 = inputFile.read(1)
        byte2 = inputFile.read(1)
        if byte1 == b'\x1f' and byte2 == b'\x8b':
            os.rename((x), (x) + ".gz")
            file = gzip.open((x), "rb")
            content = file.read()
            with open((x), "wb") as outputFile:
                outputFile.write(content)

错误:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'f_000002.gz'
4

1 回答 1

6

您应该inputFile在尝试重命名之前关闭它:

...
    inputFile = open((x), "rb")
    byte1 = inputFile.read(1)
    byte2 = inputFile.read(1)
    inputFile.close()
于 2012-12-06T16:04:18.587 回答