python - 提取并重命名 zip 文件夹

标签 python zip directory extract

我想在 python 中从一个 zip 文件中提取一个特定的文件夹,然后用原始文件名重命名它。

例如,我有一个名为 test.zip 的文件,其中包含多个文件夹和子文件夹:

xl/media/image1.png
xl/drawings/stuff.png
stuff/otherstuff.png

我想将 media 文件夹的内容提取到名为 test 的文件夹中: test/image1.png

最佳答案

使用

例如:

#!/usr/bin/env python
"""Usage:
./extract.py test.zip
"""

from zipfile import ZipFile
import os
import sys
import tempfile
import shutil


ROOT_PATH = 'xl/media/'

zip_name = sys.argv[1]
zip_path = os.path.abspath(zip_name)
extraction_dir = os.path.join(os.getcwd(), os.path.splitext(zip_name)[0])
temp_dir = tempfile.mkdtemp()


with ZipFile(zip_path, 'r') as zip_file:
    # Build a list of only the members below ROOT_PATH
    members = zip_file.namelist()
    members_to_extract = [m for m in members if m.startswith(ROOT_PATH)]
    # Extract only those members to the temp directory
    zip_file.extractall(temp_dir, members_to_extract)
    # Move the extracted ROOT_PATH directory to its final location
    shutil.move(os.path.join(temp_dir, ROOT_PATH), extraction_dir)

# Uncomment if you want to delete the original zip file
# os.remove(zip_path)

print "Sucessfully extracted '%s' to '%s'" % (zip_path, extraction_dir)

使用try..except block 来处理创建目录、删除文件和解压缩 zip 时可能发生的各种异常。

关于python - 提取并重命名 zip 文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19618268/

相关文章:

android - Kivy 添加小部件错误

python - 理解 Tensorflow 中的 while 循环

Haskell map /zip 与。列表理解

c - 为什么这个递归搜索不进入第 2 层?

python - 如何在 Tkinter 中循环显示 jpg 的子文件夹?

python - 如何使用静态变量、自定义 getter 和 setter 扩展 SWIG 中的结构?

python - Pandas Dataframe 将字符串转换为没有时间的日期

python - base64 在 Python 中编码一个 zip 文件

php - 在 PHP 中是否可以在不首先提取其内容的情况下检查 Zip 文件的内容?

Java - 如何将文件写入指定目录