2


I am trying to build a script written in Python which explore an archive (in this case a zip), and recursively gets all meta-data of files.
I usually use the following command to get meta-data:

(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(fname)

The problem is that I don't want to extract the files from the zip, so I don't have a path to provide to os.stat(). The only thing I am able to do is:

z=zipfile.ZipFile(zfilename,'r')
    for info in z.infolist():
        fname = info.filename
        data = z.read(fname)

Can I use the 'data' to get informations I need? or should I use another approach?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Labo29
  • 117
  • 3
  • 13

3 Answers3

3
with zipfile.ZipFile(path_zip_file, 'r') as zip_file:
    for elem in zip_file.infolist():
        if elem.filename.endswith('/'):
            continue
        print('year_last_modified', elem.date_time[0])
        print('month_last_modified', elem.date_time[1])

You can get file lists * .zip files using the method infolist()

To work only with files, check is used if elem.filename.endswith('/')

In order to get the year and month of creation / modification of a file, you can use elem.date_time[0] and elem.date_time[1]

  • Please don't post only code as an answer, but also provide an explanation of what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes – Ran Marciano Dec 06 '20 at 10:00
  • Thanks for writing about this! I'm new. I added comments. – Eugene Sweets Dec 07 '20 at 09:55
2

The ZIP format doesn't contain nearly as much metadata as a file on the filesystem (nor does it need to). You can extract all metadata from a zipfile without decompressing the file contents.

The ZipFile.infolist() method gives you a list of ZipInfo instances, giving you access to that metadata.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1
import os
import zipfile

z=zipfile.ZipFile(zfilename,'r')

for info in z.infolist():
    fname = info.filename
    data = z.read(fname)
    print(fname)
    print(data)
slfan
  • 8,950
  • 115
  • 65
  • 78
Suraj shah
  • 31
  • 4
  • I doubt that this helps or even works at all. To convince me otherwise, and also to help fighting the misconception that StackOverflow is a free code-writing service, please add an explanation of how this works and why it helps. – Yunnosch Jan 12 '20 at 10:30
  • what you want to know i will try my best to give explaination – Suraj shah Jan 12 '20 at 15:40
  • I want to know how this works and why it helps solving the problem. Please add the explanation to the answer, by [edit]ing it. The more you explain, the more convincing and helpful your answer is. – Yunnosch Jan 12 '20 at 16:15