2

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.

Gary
  • 4,495
  • 13
  • 36
  • 49
  • 2
    Can you share the code you are using that unzips? – Jason Sperske May 31 '13 at 21:00
  • 2
    What WinZip does is read that information from the zip metadata, then updates the creation date of the file after extracting. Both Python and WinZip have to create a new copy of the file when exctracting, that **is** truly extracting it from the zipped file. Your Python code just has to do the same thing; read the metadata and set the creation time. – Martijn Pieters May 31 '13 at 21:03

1 Answers1

2

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.

Community
  • 1
  • 1
Gareth Davidson
  • 4,857
  • 2
  • 26
  • 45