get file list of files contained in a zip file

2020-02-08 04:41发布

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

标签: python
3条回答
Juvenile、少年°
2楼-- · 2020-02-08 05:31
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.

查看更多
倾城 Initia
3楼-- · 2020-02-08 05:31
import zipfile

zip = zipfile.ZipFile('filename.zip')

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


# extract a specific file from zip 
f=zip.open("file_inside_zip.txt")
content = f.read()
f = open('extracted.txt', 'wb')
f.write(content)
f.close()
查看更多
小情绪 Triste *
4楼-- · 2020-02-08 05:36

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.

查看更多
登录 后发表回答