Reputation: 421
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
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 :
Upvotes: 0
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 oftime.time()
and of thest_mtime
attribute of the object returned byos.stat()
.
Upvotes: 2