Home > OS >  Read a file within an archived archive (without extracting)
Read a file within an archived archive (without extracting)

Time:04-12

What I am trying to do is to read a file located in an archived archive as shown below: I want to access a "document.txt" file

Code 1:

import zipfile

with zipfile.ZipFile("archive.zip", mode="r") as archive:
   with zipfile.ZipFile("archive2.zip", mode="r") as archive2:
      text = archive2.read("document.txt")
      print(text) #FileNotFountError: [Errno 2] No such file or directory: 'archive2.zip'

Code 2:

import zipfile

with zipfile.ZipFile("archive.zip/archive2.zip", mode="r") as archive:
   text = archive.read("document.txt")
   print(text) #FileNotFountError: [Errno 2] No such file or directory: 'archive.zip/archive2.zip'

None of the above works. How can I read a "document.txt" file that is located in an "archive2.zip", which in turn is located in an "archive.zip" file without extracting anything? Thank you very much.

CodePudding user response:

You need to open first then read it. Ex:-

import zipfile
with zipfile.ZipFile("archive.zip/archive2.zip", mode="r") as archive:
   text = archive.open("document.txt").read().decode()
   print(text) 

CodePudding user response:

You first need to open archive.zip, then read the raw archive2.zip file and finally read the document within that zip file.

import zipfile

with zipfile.ZipFile(r"archive.zip", "r") as archive:
    with zipfile.ZipFile(archive.open(r"archive/archive2.zip", "r")) as archive2:
        doc = archive2.open("archive2/document.txt")
        content = doc.readlines()
        print(content)
  • Related