unzip an archive without overwriting existing files
Asked Answered
J

1

13

How to unzip an archive without overwriting existing files?

The ZipFile.extractall function is extracting a ZIP file but also overwrite existing file.

So, I wrote my own function:

import os
import zipfile


def unzip(src_path, dst_dir, pwd=None):
    with zipfile.ZipFile(src_path) as zf:
        members = zf.namelist()
        for member in members:
            arch_info = zf.getinfo(member)
            arch_name = arch_info.filename.replace('/', os.path.sep)
            dst_path = os.path.join(dst_dir, arch_name)
            dst_path = os.path.normpath(dst_path)
            if not os.path.exists(dst_path):
                zf.extract(arch_info, dst_dir, pwd)

But, a full implementation could require to re-implement the extract method.

Is there any way to unzip an archive ignoring the existing files? An equivalent of unzip -n arch.zip?

Jackdaw answered 21/4, 2020 at 19:9 Comment(1)
I would also like this feature!Collywobbles
S
1

Python does not have a built-in option to prevent overwriting existing files when using the zipfile.ZipFile.extractall() method. To achieve this behavior, you would need to implement your own function like the one you have written.

 def unzip_without_overwrite(src_path, dst_dir):
        with zipfile.ZipFile(src_path, "r") as zf:
            for member in zf.infolist():
                file_path = os.path.join(dst_dir, member.filename)
                if not os.path.exists(file_path):
                    zf.extract(member, dst_dir)
Schwab answered 26/1, 2023 at 13:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.