首页 > 解决方案 > 使用python将目录内的压缩文件夹中的所有文件提取到没有文件夹的其他目录

问题描述

# importing required modules
from zipfile import ZipFile

# specifying the zip file name

file_name = "C:\\OPR\\109521P.zip"

# opening the zip file in READ mode
 with ZipFile(file_name, 'r') as zip:
 # printing all the contents of the zip file
  result =zip.printdir()

  # extracting all the files
  print('Extracting all the files now...')
  zip.extractall('images')
  print('Done!')

我在压缩文件夹的子文件夹中压缩了大约 10 张图像,现在我想将所有图像直接提取到其他目录而不使用子文件夹,我尝试使用 os.path.basename(name),但我得到了严重错误。

在上面的代码之后,我得到一个文件夹中的所有图像,,

C:\图像\109521P

以上是提取所有 10 张图像的输出位置,现在我希望直接提取图像

C:\图像

所以我想省略子文件夹 109521P 并希望在上面的位置直接提取图像。

标签: pythonimagezipsubdirectory

解决方案


my_dir = r"C:\OPR"
my_zip = r"C:\OPR\109521P.zip"

with zipfile.ZipFile(my_zip) as zip_file:
   for member in zip_file.namelist():
    filename = os.path.basename(member)
    # skip directories
    if not filename:
        continue

    # copy file (taken from zipfile's extract)
    source = zip_file.open(member)
    target = open(os.path.join(my_dir, filename), "wb")
    with source, target:
        shutil.copyfileobj(source, target)

我得到了答案,只是发布它


推荐阅读