4

I have this current code to unzip the contents of archive to extract_dir. However, I cannot figure out how to get the extracted file path & name of the extracted file.

if archive.endswith((".zip")):
    zip_ref = zipfile.ZipFile(archive, 'r')
    zip_ref.extract(extract_dir)
    zip_ref.close()

For example, if the archive is called test.zip and ZipFile extracts the contents test.exe I want get C:/windows/users/admin/downloads/test.exe in to a variable?

EDIT: Sorry I wasn't clear, in the source code for zipfile targetpath is returned I am wondering how I can get this?

Dharman
  • 30,962
  • 25
  • 85
  • 135
user7399815
  • 323
  • 1
  • 3
  • 10
  • What if there are multiple files in the zip? – Willem Van Onsem Mar 10 '17 at 10:51
  • That's not a zipfile issue. If you extracted files to a specific location (and you obviously know the location), and you want to get the files from there, you'll have to e.g. `os.walk` in that dir to get all files into a data structure. – nir0s Mar 10 '17 at 10:55
  • If you don't supply a `path` arg to `ZipFile.extract` the archive members are extracted to the current working dir. You can get the list of archive members by name with [`zip_ref.namelist()`](https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.namelist). – PM 2Ring Mar 10 '17 at 10:58
  • @WillemVanOnsem then I would use extractall but that isn't a problem right now. – user7399815 Mar 10 '17 at 11:06
  • @PM2Ring I'll try using that i was just trying to do it a bit cleaner by using the `targetpath` the is is returned to the extract function in zipfile – user7399815 Mar 10 '17 at 11:07
  • The 1st arg to `ZipFile.extract` must be the member you want to extract, either in the form of a string, or a `ZipInfo` object. The path to extract can be given after the member arg. – PM 2Ring Mar 10 '17 at 11:49

1 Answers1

13

Here is the solution, I can't accept the answer for 2 days though.

if archive.endswith((".zip")):
    print "example.jpg"
    zip_ref = zipfile.ZipFile(archive, 'r')
    extracted = zip_ref.namelist()
    zip_ref.extractall(extract_dir)
    zip_ref.close()
    extracted_file = os.path.join(extract_dir, extracted[0])
algorithms
  • 1,085
  • 1
  • 12
  • 21
user7399815
  • 323
  • 1
  • 3
  • 10