gpt4 book ai didi

python - 压缩文件并保留修改时间戳

转载 作者:太空宇宙 更新时间:2023-11-04 09:05:55 24 4
gpt4 key购买 nike

我坚持设置文件时间戳,也是根据 python gzip document ,语法不像 gzip.GzipFile(filename=outputfile,mode='wb',compresslevel=9,mtime=ftime) 那样工作,但是当我使用 gzip.GzipFile(outputfile,' wb',9,mtime=ftime) 它正在工作,但时间戳除外。

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)

这里是输出:

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

最佳答案

正如您在 documentation 中看到的那样, mtime 参数是写入流的时间戳,它不会影响创建的 gzip 文件的时间戳。如果使用 gunzip -N 解压缩,这是解压缩文件将具有的时间戳。

例子:

>>> 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()

并解压:

$ gunzip -N test.gz
$ stat -c%y test
2010-11-12 13:14:00.000000000 +0100

如果您希望创建的 gzip 文件具有特定的时间戳,请使用 os.utime改变它:

...
st = os.stat(file)
...
os.utime(outputfile, (st.st_atime, st.st_mtime))
...

关于python - 压缩文件并保留修改时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20856987/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com