You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python直接实现unzip -p功能?是否需调用subprocess?

纯Python实现提取XLSX中的sharedStrings.xml内容

当然可以!完全不需要借助subprocess调用外部unzip命令,Python自带的zipfile模块就能完美实现这个需求——毕竟XLSX文件本质就是一个ZIP压缩包,我们直接操作这个压缩包就行,还更跨平台、更可控。

基础实现(一次性读取写入)

这个版本和你用unzip -p的效果完全一致,代码简洁直观:

import zipfile

# 替换成你的文件路径
xlsx_file = "/Users/david/Desktop/new2.xlsx"
output_file = "shared3.xml"

# 用with语句自动处理文件打开/关闭,更安全
with zipfile.ZipFile(xlsx_file, 'r') as zip_archive:
    # 直接读取压缩包内的xl/sharedStrings.xml文件
    with zip_archive.open('xl/sharedStrings.xml') as xml_content:
        # 将内容写入到目标文件
        with open(output_file, 'wb') as out_file:
            out_file.write(xml_content.read())

大文件优化(逐块读写)

如果你的XLSX文件特别大,一次性读取整个XML内容到内存可能会有压力,可以改成逐块读写的方式:

import zipfile

xlsx_file = "/Users/david/Desktop/new2.xlsx"
output_file = "shared3.xml"

chunk_size = 1024 * 1024  # 每次读取1MB的块,可根据需求调整

with zipfile.ZipFile(xlsx_file, 'r') as zip_archive:
    with zip_archive.open('xl/sharedStrings.xml') as xml_content:
        with open(output_file, 'wb') as out_file:
            while chunk := xml_content.read(chunk_size):
                out_file.write(chunk)

为什么比subprocess更好?

  • 不需要依赖系统上的unzip命令,跨Windows/macOS/Linux都能运行
  • 完全在Python环境内处理,更容易捕获和处理错误
  • 避免了shell命令注入的风险(如果路径是动态生成的话)

内容的提问来源于stack exchange,提问作者David542

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 16:57:44