【问题标题】:Python: Attempt to use ZIP archive that was already closedPython:尝试使用已关闭的 ZIP 存档
【发布时间】:2021-09-23 04:29:45
【问题描述】:

我想打开一个压缩文件A001-C-002.zip。它引发Attempt to use ZIP archive that was already closed 错误。

from pathlib import Path
import pandas as pd
import zipfile
import os
import sys

path = "./CODEX/input/"

for filename in os.listdir(os.getcwd()):
    with open(os.path.join(os.getcwd(), filename), 'r') as f:
        # Antibody information
        ab = pd.read_excel("HUBMAP B004 codex antibodies metadata.xlsx")
        print(f"Antibody metadata column names:\n {ab.columns.values}")
        
        # Patient A001
        with zipfile.ZipFile("A001-C-002.zip") as z:
            for filename in z.namelist():
                if not os.path.isdir(filename):
                    for line in z.open(filename):
                        print(line)
                    z.close()

追溯:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/tmp/ipykernel_4872/558093962.py in <module>
      9             for filename in z.namelist():
     10                 if not os.path.isdir(filename):
---> 11                     for line in z.open(filename):
     12                         print(line)
     13                     z.close()

/usr/lib/python3.8/zipfile.py in open(self, name, mode, pwd, force_zip64)
   1499             raise ValueError("pwd is only supported for reading files")
   1500         if not self.fp:
-> 1501             raise ValueError(
   1502                 "Attempt to use ZIP archive that was already closed")
   1503 

ValueError: Attempt to use ZIP archive that was already closed

【问题讨论】:

  • 你在打印一个文件后调用z.close(),然后它就关闭了:)
  • 您在使用with 时无需致电close()。当你离开区块时它会自动关闭它。

标签: python zipfile


【解决方案1】:

你的麻烦来自代码的最后三行:

                for line in z.open(filename):
                    print(line)
                z.close()

您似乎希望 z.close 调用关闭您在这些行的第一行中打开的文件。但这不是它的作用。 z 是您一直在扫描的整个 zip 存档,当您关闭它时,您将无法再次打开其中包含的任何文件(无论如何都要重新打开整个文件)。

我怀疑你想要更像这样的东西:

with z.open(filename) as file:
    for line in file:
        print(line)

这里我们使用with 语句来处理归档中内部文件的关闭,该文件始终保持打开状态(直到外部with 语句结束)。我为该文件对象命名为file,以便with 语句可以将其交给for 循环。

【讨论】:

    猜你喜欢
    • 2013-07-01
    • 2015-06-16
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多