python处理【orc】下载压缩的.zip文件,windows和linux同时适配

一. 前言

在Python中处理ZIP文件时,要实现Windows和Linux的跨平台适配问题。

二. 代码

python 复制代码
import os
import zipfile
from pathlib import Path
import re


def extract_preserve_structure(zip_path: str, extract_to: str):
    """
    解压 ZIP,自动剥离绝对路径前缀,保留任务目录下的完整子结构。
    假设有效内容位于某个纯数字目录(如 123/)之下。
    """
    with zipfile.ZipFile(zip_path, 'r') as zip_ref:

        for file_info in zip_ref.infolist():
            # 安全地处理路径,去除绝对路径和危险字符
            original_name = file_info.filename
            safe_name = os.path.normpath(original_name).lstrip('/\\')
            safe_name = safe_name.lstrip('.' + os.sep)

            # 跳过以斜杠开头的绝对路径
            if safe_name.startswith('/') or ':' in safe_name:
                safe_name = os.path.basename(safe_name)

            target_path = Path(extract_to) / safe_name
            
            # 如果是目录,创建目录
            if original_name.endswith('/'):
                target_path.mkdir(parents=True, exist_ok=True)
            else:
                # 确保父目录存在
                target_path.parent.mkdir(parents=True, exist_ok=True)

                # 解压文件
                with zip_ref.open(file_info) as src:
                    with open(target_path, 'wb') as dst:
                        dst.write(src.read())
                        
            print(f"已解压: {original_name} -> {target_path}")


zip_path = '20251114_175148_d33b98204c084b81bf56e8277097a0f5 - 副本.zip'
extract_to = '.'
extract_preserve_structure(zip_path, extract_to)
         

三. 总结

  • 路径分隔符:始终使用/作为ZIP内部路径分隔符
  • 文件权限:在非Windows系统上正确处理UNIX文件权限
  • 编码问题:处理文件名编码,支持中文等特殊字符
  • 路径安全:防止ZIP路径遍历攻击
  • 符号链接:根据需要处理符号链接(默认不跟随)
相关推荐
曲幽6 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时10 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
木心月转码ing10 小时前
WSL+Cpp开发环境配置
linux
哈里谢顿12 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi1 天前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee1 天前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay1 天前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python
闲云一鹤1 天前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi