使用文件路径写入TXT到Zip时生成冗余目录的解决咨询
解决方案
核心思路是分离文件的实际路径和压缩包内的条目名称:用完整路径读取文件,仅用纯文件名作为压缩包内的条目名,避免生成嵌套目录结构。
方法1:使用os.path.basename()提取文件名
修改后的代码:
import os from zipfile import ZipFile, ZIP_DEFLATED file_paths = ['/tmp/bmex-2023-07-28-w0hrsh25/MFII_MC_TICK_H_20230703.TXT', '/tmp/bmex-2023-07-28-w0hrsh25/MFII_MC_TICK_AE_20230703.TXT'] with ZipFile(str(new_file), 'w', compression=ZIP_DEFLATED) as merged_archive: for file in file_paths: # 从完整路径中提取纯文件名 file_name = os.path.basename(file) # 用完整路径打开文件确保能找到 with open(file, 'r') as f: # 写入压缩包时指定条目名为纯文件名 merged_archive.writestr(file_name, f.read())
方法2:用pathlib模块(Python 3.4+)
更现代的路径处理方式:
from pathlib import Path from zipfile import ZipFile, ZIP_DEFLATED file_paths = ['/tmp/bmex-2023-07-28-w0hrsh25/MFII_MC_TICK_H_20230703.TXT', '/tmp/bmex-2023-07-28-w0hrsh25/MFII_MC_TICK_AE_20230703.TXT'] with ZipFile(str(new_file), 'w', compression=ZIP_DEFLATED) as merged_archive: for file in file_paths: path_obj = Path(file) with open(path_obj, 'r') as f: merged_archive.writestr(path_obj.name, f.read())
方法3:直接用ZipFile.write()(更简便)
无需手动打开文件,write()方法支持指定压缩包内的条目名:
import os from zipfile import ZipFile, ZIP_DEFLATED file_paths = ['/tmp/bmex-2023-07-28-w0hrsh25/MFII_MC_TICK_H_20230703.TXT', '/tmp/bmex-2023-07-28-w0hrsh25/MFII_MC_TICK_AE_20230703.TXT'] with ZipFile(str(new_file), 'w', compression=ZIP_DEFLATED) as merged_archive: for file in file_paths: # arcname参数指定文件在压缩包内的名称,这里设为纯文件名 merged_archive.write(file, arcname=os.path.basename(file))
以上三种方法都能让生成的压缩包内仅包含两个文本文件,不会带嵌套目录结构。
内容的提问来源于stack exchange,提问作者ifrj
相关产品推荐
相关产品推荐

