获取压缩文件中包含的文件列表

我有一个压缩档案: my_zip.zip。我当时正在查看 Python 的 zipfile模块(http://docs.python.org/library/zipfile.html) ,但是对我要做的事情没有太多的了解。

我将如何做相当于“双击”zip 文件获取 txt 文件,然后使用 txt 文件,这样我就可以:

>>> f = open('my_txt_file.txt','r')
>>> contents = f.read()
111056 次浏览
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.

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.

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