简体   繁体   中英

get file list of files contained in a zip file

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

您需要的是ZipFile.namelist()它将为您提供存档所有内容的列表,然后您可以执行zip.open('filename_you_discover')以获取该文件的内容。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM