如何在Linux上使用gzip压缩文件并保留时间戳

2024-09-30 18:14:47 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: 文件函数in命令close时间互联网open
2条回答

如果使用Python2.6,则zlib模块无法调整写入gz文件的mtime。你只剩下两种方法:

  • 升级到python2.7,使用stat/fstat获取原始文件的mtime并将其写入gz文件
  • 通过subprocess模块使用Linux系统的gzip实用程序。在

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

相关问题 更多 >