如何从Zip文件提取单个指定文件而非完整目录?能否用shutil?
解决方案:提取Zip文件中的单个文件而不保留目录结构
嗨,我来帮你搞定这个问题!你现在的代码会保留Zip里的完整目录结构,是因为zipfile.ZipFile.extract()方法默认会按照文件在压缩包内的相对路径来创建目录并提取文件。要只把AccountService.json复制到目标目录,有两种简单的方法,其中就包括用shutil实现的方案:
方法一:使用zipfile直接读写文件内容
这种方法通过直接读取压缩包内的文件内容,再写入到目标目录的同名文件中,跳过中间目录的创建:
import os import zipfile zip_filepath='/home/sundeep/Desktop/SCHEMA AUTOMATION/SOURCE/DSP8010_2017.1.zip' target_dir='/home/sundeep/Desktop/SCHEMA AUTOMATION/SCHEMA' # 确保目标目录存在,避免写入时报错 os.makedirs(target_dir, exist_ok=True) with zipfile.ZipFile(zip_filepath) as zf: # 定义压缩包内目标文件的路径 zip_internal_path = 'DSP8010_2017.1/json-schema/AccountService.json' # 提取文件名(去掉前面的目录部分) filename = os.path.basename(zip_internal_path) # 拼接目标文件的完整路径 target_file_path = os.path.join(target_dir, filename) # 读取压缩包内的文件并写入到目标路径 with zf.open(zip_internal_path) as source_file, open(target_file_path, 'wb') as dest_file: dest_file.write(source_file.read())
方法二:用shutil简化文件复制操作
当然可以用shutil实现!shutil.copyfileobj()方法专门用于复制文件对象,比手动读写更高效(尤其是处理大文件时会分块读取,节省内存):
import os import zipfile import shutil zip_filepath='/home/sundeep/Desktop/SCHEMA AUTOMATION/SOURCE/DSP8010_2017.1.zip' target_dir='/home/sundeep/Desktop/SCHEMA AUTOMATION/SCHEMA' # 先确保目标目录存在 os.makedirs(target_dir, exist_ok=True) with zipfile.ZipFile(zip_filepath) as zf: zip_internal_path = 'DSP8010_2017.1/json-schema/AccountService.json' filename = os.path.basename(zip_internal_path) target_file_path = os.path.join(target_dir, filename) # 用shutil复制文件对象 with zf.open(zip_internal_path) as source_file, open(target_file_path, 'wb') as dest_file: shutil.copyfileobj(source_file, dest_file)
两种方法都能达到你的需求:只把AccountService.json文件复制到指定的target_dir,不会创建DSP8010_2017.1/json-schema这些中间目录。
内容的提问来源于stack exchange,提问作者kishore
相关产品推荐
相关产品推荐

