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

如何在Python中合并压缩包内的多个.txt文件为单个文件?

解决ZIP压缩包内TXT文件合并问题

原代码的核心问题

直接通过Path指向ZIP包内的文件路径是无效的——ZIP是压缩容器,并非普通文件系统目录,Python的open()函数无法直接识别这种嵌套路径,必须通过专门的压缩包处理模块读取内部文件。

修复后的实现代码

使用Python标准库zipfile操作ZIP包,读取其中的TXT文件并合并:

import zipfile
import shutil

# 定义ZIP包路径和要合并的内部文件名
zip_path = r'C:\Users\Viniz\Downloads\devkmbe-5511001_05-12-2022_00_20_09.zip'
target_files = [
    'AudioCaptureMemoryUsage_01_12_2022.txt',
    'AudioMatchingMemoryUsage_01_12_2022.txt'
]

newfile = input("Enter the name of the new file: ")
print(f"\nThe merged content of the 2 files will be in {newfile}")

# 打开目标文件并写入合并内容
with open(newfile, "wb") as wfd:
    # 打开ZIP压缩包
    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        for file_name in target_files:
            # 从ZIP包中读取内部文件
            with zip_ref.open(file_name, 'r') as fd:
                shutil.copyfileobj(fd, wfd, 1024 * 1024 * 10)

print("\nThe content is merged successfully.!")
print("Do you want to view it ? (y / n): ")

check = input().strip().lower()
if check == 'n':
    exit()
else:
    print()
    with open(newfile, "r") as c:
        print(c.read())

关键优化点

  • 用zipfile.ZipFile打开压缩包,通过zip_ref.open()读取内部文件,这是Python处理ZIP包内文件的标准方式
  • 保留原代码的高效合并逻辑(shutil.copyfileobj大块复制内容),仅修复文件读取的核心问题
  • 新增strip().lower()处理用户输入,避免大小写或空格导致的判断失误
  • 读取合并后的文件时改用with语句,确保文件自动关闭,避免资源泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 14:25:30