78

I have a zip archive: my_zip.zip. Inside it is one txt file, the name of which I do not know. I was taking a look at Python's zipfile module ( http://docs.python.org/library/zipfile.html ), but couldn't make too much sense of what I'm trying to do.

How would I do the equivalent of 'double-clicking' the zip file to get the txt file and then use the txt file so I can do:

>>> f = open('my_txt_file.txt','r')
>>> contents = f.read()
sophros
  • 8,714
  • 5
  • 30
  • 57
David542
  • 96,524
  • 132
  • 375
  • 637

3 Answers3

110

What you need is ZipFile.namelist() that will give you a list of all the contents of the archive, you can then do a zip.open('filename_you_discover') to get the contents of that file.

  • 4
    Or use [`infolist()`](https://docs.python.org/2/library/zipfile.html#zipfile.ZipFile.infolist) if you want to get other details; like the Date Modified or Compressed Size – The Red Pea Apr 07 '15 at 15:23
  • 9
    Is there a method that returns the file names as an iterator rather than a list? – Elliott Sep 14 '16 at 20:25
  • https://gist.github.com/berezovskyi/c440125e10fc013a36f6f5feb8bc3117 is a short hack I wrote for myself to use a generator as `for f in itertar(tarfile):` – berezovskyi Dec 27 '20 at 21:21
26
import zipfile

# zip file handler  
zip = zipfile.ZipFile('filename.zip')

# list available files in the container
print (zip.namelist())

# extract a specific file from the zip container
f = zip.open("file_inside_zip.txt")

# save the extraced file 
content = f.read()
f = open('file_inside_zip.extracted.txt', 'wb')
f.write(content)
f.close()
J. Ceron
  • 509
  • 5
  • 6
20
import zipfile

zip=zipfile.ZipFile('my_zip.zip')
f=zip.open('my_txt_file.txt')
contents=f.read()
f.close()

You can see the documentation here. In particular, the namelist() method will give you the names of the zip file members.

President James K. Polk
  • 36,717
  • 16
  • 86
  • 116
  • 2
    I get an error saying that "There is no item named '' in the archive". Note that I **do not know** what the name of the file that is zipped is called (and it is different than the name of the zip archive). – David542 Jan 13 '12 at 02:12