You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python gzip模块压缩文件并保留原文件时间戳

如何用Python的gzip模块保留原文件时间戳

Python的gzip模块默认会将压缩文件的时间戳设为当前时间,但gzip格式本身支持存储原始文件的修改时间戳,只需手动指定参数即可实现和Linux系统gzip命令一致的效果。

实现步骤

  1. 获取原文件的修改时间戳:通过os.path.getmtime()或os.stat()获取原文件的st_mtime属性。
  2. 创建gzip压缩文件时,通过mtime参数将获取到的时间戳传入。

代码示例

方法一:使用gzip.GzipFile

import gzip
import os

def gzip_preserve_mtime(source, target):
    # 获取原文件的修改时间戳
    original_mtime = os.path.getmtime(source)
    # 读取原文件并写入压缩文件,同时指定mtime参数
    with open(source, 'rb') as src_f:
        with gzip.GzipFile(target, 'wb', mtime=original_mtime) as dst_f:
            dst_f.write(src_f.read())

方法二:使用gzip.open

import gzip
import os

src_path = "test.txt"
dst_path = "test.txt.gz"

# 获取原文件的状态信息,提取修改时间
file_stats = os.stat(src_path)
with open(src_path, 'rb') as in_file:
    with gzip.open(dst_path, 'wb', mtime=file_stats.st_mtime) as out_file:
        out_file.write(in_file.read())

验证效果

压缩完成后,用Linux的gzip -l命令查看压缩文件的时间戳,会发现它和原文件的修改时间完全一致,和系统gzip命令的效果相同。

内容的提问来源于stack exchange,提问作者Suresh Subramaniyan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 17:18:10