Search code examples
pythonmetadatagzip

How to get the metadata of a file compressed in a gzip archive?


I have a very basic request.

All I need is to retreive the modification time of my_text.txt compressed in my_archive.gz.

enter image description here

from gzip import GzipFile

with GzipFile('my_archive.gz') as gzip_file:
    print(gzip_file.getinfo('my_text.txt').date_time)

This code is giving me this error : AttributeError: 'GzipFile' object has no attribute 'getinfo'

When I try print(gzip_file.mtime), I get None.

I expect this output : (2023, 11, 13, 10, 9, 42)

I'm so confused guys. Why Python can't retrieve this info while a tool like 7zip can ?


Solution

  • As you can read between the lines in the documentation of .mtime, you need to first call .peek(n) with some number of bytes for n. Otherwise, the decompression hasn't started at all, the underlying file hasn't been accessed and therefore no (meta-)information is available.