我有一个 zip 存档:my_zip.zip
. 里面是一个txt文件,我不知道它的名字。我正在查看 Python 的zipfile
模块(http://docs.python.org/library/zipfile.html),但对我正在尝试做的事情不太了解。
我将如何做相当于“双击” zip 文件以获取 txt 文件,然后使用 txt 文件,这样我就可以做到:
>>> f = open('my_txt_file.txt','r')
>>> contents = f.read()
我有一个 zip 存档:my_zip.zip
. 里面是一个txt文件,我不知道它的名字。我正在查看 Python 的zipfile
模块(http://docs.python.org/library/zipfile.html),但对我正在尝试做的事情不太了解。
我将如何做相当于“双击” zip 文件以获取 txt 文件,然后使用 txt 文件,这样我就可以做到:
>>> f = open('my_txt_file.txt','r')
>>> contents = f.read()
您需要的是ZipFile.namelist()
为您提供存档所有内容的列表,然后您可以执行 azip.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()
您可以在此处查看文档。特别是,该namelist()
方法将为您提供 zip 文件成员的名称。