如何在不覆盖现有文件的情况下解压缩存档?
该ZipFile.extractall功能是在提取 ZIP 文件的同时覆盖现有文件。
所以,我写了自己的函数:
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)
Run Code Online (Sandbox Code Playgroud)
但是,完整的实现可能需要重新实现该extract方法。
有没有办法解压缩存档而忽略现有文件?相当于unzip -n arch.zip?
小智 1
Python 没有内置选项来防止使用 zipfile.ZipFile.extractall() 方法时覆盖现有文件。为了实现这一行为,您需要实现您自己的函数,就像您编写的函数一样。
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
563 次 |
| 最近记录: |