unzip file in python but don't change file cre

2020-06-25 06:13发布

问题:

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.

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

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

another version:

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)

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

回答1:

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.

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

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.

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.

Not sure about BSD or other operating systems.



标签: python zip