
Question:
I'm stuck with setting up file time stamp, also as per python <a href="http://www.afpy.org/doc/python/2.7/library/gzip.html" rel="nofollow">gzip document</a> , the syntax not working like gzip.GzipFile(filename=outputfile,mode='wb',compresslevel=9,mtime=ftime)
, but when I used gzip.GzipFile(outputfile,'wb',9,mtime=ftime)
it's working but except time stamp.
def compresse_file(file,ftime):
data = open(file,'rb')
outputfile = file +".gz"
gzip_file = gzip.GzipFile(outputfile,'wb',9,mtime=ftime)
gzip_file.write(data.read())
gzip_file.flush()
gzip_file.close()
data.close()
os.unlink(file)
Here is output :
root@ubuntu:~/PythonPractice-# python compresses_file.py
Size Date File Name
5 MB 30/12/13 test.sh
Compressing...
test.sh 1388403823.0
file status after compressesion
5 kB 31/12/13 test.sh.gz
root@ubuntu:~/PythonPractice-# date -d @1388403823.0
Mon Dec 30 17:13:43 IST 2013
Answer1:As you can see in the <a href="http://docs.python.org/3.3/library/gzip#gzip.GzipFile" rel="nofollow">documentation</a>, the mtime
argument is the timestamp that is written to the stream, it doesn't affect the timestamp of the created gzip file. This is the timestamp the decompressed file will have if decompressed using gunzip -N
.
Example:
>>> import datetime
>>> import gzip
>>> ts = datetime.datetime(2010, 11, 12, 13, 14).timestamp()
>>> zf = gzip.GzipFile('test.gz', mode='wb', mtime=ts)
>>> zf.write(b'test')
>>> zf.flush()
>>> zf.close()
And decompressed:
<pre class="lang-none prettyprint-override">$ gunzip -N test.gz
$ stat -c%y test
2010-11-12 13:14:00.000000000 +0100
If you want the created gzip file to have a specific timestamp, use <a href="http://docs.python.org/3.3/library/os#os.utime" rel="nofollow">os.utime</a> to change it:
...
st = os.stat(file)
...
os.utime(outputfile, (st.st_atime, st.st_mtime))
...