Extract zip to memory, parse contents

前端 未结 4 801
孤独总比滥情好
孤独总比滥情好 2021-01-22 21:30

I want to read the contents of a zip file into memory rather than extracting them to disc, find a particular file in the archive, open the file and extract a line from it.

4条回答
  •  囚心锁ツ
    2021-01-22 22:16

    The question you link shows you that you need to read the file. Depending on your use case that may already be enough. In your code you replace the loop variable holding a filename with an empty string buffer. Try something like this:

    zfile = ZipFile('name.zip', 'r')
    
    for name in zfile.namelist():
        if fnmatch.fnmatch(name, '*_readme.xml'):
            ex_file = zfile.open(name) # this is a file like object
            content = ex_file.read() # now file-contents are a single string
    

    If you really want a buffer that you can manipulate, then simply instantiate it with the contents:

    buf = StringIO(zfile.open(name).read())
    

    You may also want to look at BytesIO and note that there are differences between Python 2 and 3.

提交回复
热议问题