Skip to content

Instantly share code, notes, and snippets.

@tkanmae
Last active January 1, 2016 00:09
Show Gist options
  • Save tkanmae/8064625 to your computer and use it in GitHub Desktop.
Save tkanmae/8064625 to your computer and use it in GitHub Desktop.
`ZipFile.extractall()` does not preserve file attributes. See http://stackoverflow.com/a/9813471
import os
import time
import zipfile
def extract_zipfile(filename, dest_dir):
"""Extract all files in a ZIP file while preserving date and time.
See http://stackoverflow.com/a/9813471.
"""
with zipfile.ZipFile(filename) as zh:
for f in zh.infolist():
if f.filename.endswith(os.path.sep):
dir_ = os.path.join(dest_dir, f.filename)
if not os.path.isdir(dir_):
os.mkdir(dir_, 0755)
continue
file_ = os.path.join(dest_dir, f.filename)
with open(file_, 'wb') as fh:
fh.write(zh.open(f).read())
date_time = time.mktime(f.date_time + (0, 0, -1))
os.utime(file_, (date_time, date_time))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment