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路径遍历攻击
  • 符号链接:根据需要处理符号链接(默认不跟随)
相关推荐
超绝振刀怪1 分钟前
【Linux工具】环境基石:软件包管理器 yum 与 Vim 编辑器详解
linux·编辑器·vim
愈努力俞幸运3 分钟前
Python heapq (堆/优先队列)
python
SHolmes18544 分钟前
给定某日的上班时间段,计算当日的工作时间总时长(Python)
开发语言·前端·python
C嘎嘎嵌入式开发11 分钟前
NLP 入门:从原理到实战的个人经验总结
人工智能·python·自然语言处理·nlp
咖啡の猫12 分钟前
Python字典元素的增、删、改操作
java·开发语言·python
Swizard13 分钟前
Python 并不慢,是你看不懂:拆解 CPython 虚拟机背后的魔法引擎
python
自由生长202421 分钟前
一次“虚拟环境复制引发的血案”:记一次 itsdangerous 版本混乱排查全过程
python
福尔摩斯张31 分钟前
插件式架构:解耦与扩展的艺术与实践(超详细)
linux·服务器·网络·网络协议·tcp/ip
txzz888840 分钟前
CentOS-Stream-10 搭建YUM源Web服务器
linux·运维·centos·yum源·linux系统更新·centos系统更新·自建web yum源
Molesidy1 小时前
【Linux】基于Imx6ull Pro开发板和platform_device+platform_driver框架的LED驱动设计以及上机测试
linux·驱动开发