在python中解压缩文件但不更改文件创建时间 [英] unzip file in python but don't change file created time

查看:47
本文介绍了在python中解压缩文件但不更改文件创建时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了多种使用 Python 解压缩文件的方法,但每种方法都以错误的创建时间结束(因为 Python 创建了该文件的新副本,而不是真正从压缩文件中提取它).例如,在 2012-12-21 上创建的文件在使用 Python 提取时将显示今天的创建日期,但如果我使用其他东西(如 WinZip),则文件创建时间不会改变.

I've tried multiple approaches to unzipping a file with Python, but each approach ends up with the wrong created time (because Python created a new copy of that file, not truly extracting it from the zipped file). For example, a file created on 2012-12-21 will show a creation date of today when extracted with Python, but if I use something else (like WinZip) the file creation time is not changed.

有没有办法在不改变创建时间的情况下使用 Python 解压文件?

Is there a way to unzip the file using Python without changing the creation time?

@Jason Sperske,这是我正在使用的代码:

@Jason Sperske, here is the code I am using:

   zf = zipfile.ZipFile(fn)
   for name in zf.namelist():
        filename = os.path.basename(name)
        zf.extract(name, filepath)
    zf.close()

另一个版本:

zf = zipfile.ZipFile(fn)
for name in zf.namelist():
    source = zf.open(name)
    target = open(os.path.join(filepath, filename), "wb")
    with source, target:
    shutil.copyfileobj(source, target)

我还在 python 中调用了 winzip,它可以工作,但很烦人.它打开了许多窗口探索窗口.

I also called winzip from within python, it works but it's annoying. It opens lots of windows explore windows.

推荐答案

Python 中没有通用的方法来设置文件的创建时间,可以使用 os.utime 来设置修改和不过访问时间.

There's no generic way to set the creation time of a file in Python, you can use os.utime to set the modification and access times though.

在 Windows 文件系统上,您可以使用 win32file 来指定创建文件的时间.请参阅这个答案 了解详情.

On Windows filesystems you can use win32file to specify the time when creating the file. See this answer for details.

在 Linux 文件系统上,并没有真正的创建日期",只有 inode 的最后修改时间戳.要编辑它,您需要破解文件系统本身(在卸载时),更改系统时间或破解内核以允许编辑 inode.这个答案显示了后两者的解决方案.

On Linux filesystems there isn't really a "creation date" as such, only the inode's last modify timestamp. To edit this you need to hack the filesystem itself (while unmounted), change the system time or hack the kernel to allow editing inodes. This answer shows solutions for the latter two.

在 Mac 上,您可以调用 setfile -d 来更改创建日期,但您必须先安装它.您可以在此处找到其文档.

On a Mac you can call setfile -d to change the creation date, though you'll have to install it first. You can find its docs here.

不确定 BSD 或其他操作系统.

Not sure about BSD or other operating systems.

这篇关于在python中解压缩文件但不更改文件创建时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆