如何使用Python gzip模块压缩文件并保留原文件时间戳
如何用Python的gzip模块保留原文件时间戳
Python的gzip模块默认会将压缩文件的时间戳设为当前时间,但gzip格式本身支持存储原始文件的修改时间戳,只需手动指定参数即可实现和Linux系统gzip命令一致的效果。
实现步骤
- 获取原文件的修改时间戳:通过
os.path.getmtime()或os.stat()获取原文件的st_mtime属性。 - 创建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
相关产品推荐
相关产品推荐

