melololo
melololo

Reputation: 171

Python: Attempt to use ZIP archive that was already closed

I want to open a zip file A001-C-002.zip. Its raising Attempt to use ZIP archive that was already closed error.

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()

Traceback:

---------------------------------------------------------------------------
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

Upvotes: 0

Views: 1421

Answers (1)

Blckknght
Blckknght

Reputation: 104682

Your trouble comes from the last three lines of your code:

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

It looks like you want the z.close call to be closing the file you opened in the first of these lines. But that's not what it does. z is the whole zip archive you've been scanning, and when you close it, you won't be able to open any of the files it contains again (not without reopening the whole thing anyway).

I suspect you want something more like this:

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

Here we use a with statement to handle the closing of the inner file within the archive, which remains open throughout (until the outer with statement ends). I give a name to that file object, file so that the with statement can hand it off to the for loop.

Upvotes: 1

Related Questions