Skip to main content
 首页 » 编程设计

python之如何 gzip 文件并在 Linux 上保留时间戳

2024年10月25日8bhlsheji

我一直在整个互联网上搜索,但我无法找到如何使用 python 对日志文件进行 gzip 压缩并保留日志文件时间戳。我查看了 python 提供的 gzip 函数,但是因为它读取数据然后输出它,所以它覆盖了文件的时间戳。我需要它的行为就像我对文件运行 linux gzip 命令一样。有什么办法吗?

    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

请您参考如下方法:

来自 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().