Ura718
Ura718

Reputation: 421

How to gzip file and preserve timestamp on linux

I been searching all over the internet but I am unable to find how to use python to gzip a log file and preserve the log file timestamp. I looked at gzip function that python provides but because it reads the data in and then outputs it, it overrides the timestamp of the file. I need it to behave exactly as if I ran a linux gzip command against a file. Is there any way to do this?

    try:
      f_in=open(file,'rb')
      f_out=gzip.open(file + '.gz','wb')
      f_out.writelines(f_in)
      f_out.close()
      f_in.close()
    
      # delete copy that gzip creates during gzip process
      os.unlink(file)

    except IOError, e:
      print "Cant Gzip %s: File not found " % file

Upvotes: 1

Views: 4858

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148975

If you use Python 2.6, the zlib module has no possibility to tweak the mtime that is written into the gz file. You are left with only two ways :

  • upgrade to Python 2.7, use stat/fstat to get the mtime of the original file and write it into the gz file
  • use the gzip utility of the Linux system through the subprocess module.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798814

From the documentation:

The mtime argument is an optional numeric timestamp to be written to the stream when compressing. All gzip compressed streams are required to contain a timestamp. If omitted or None, the current time is used. This module ignores the timestamp when decompressing; however, some programs, such as gunzip, make use of it. The format of the timestamp is the same as that of the return value of time.time() and of the st_mtime attribute of the object returned by os.stat().

Upvotes: 2

Related Questions