Python 解压缩并重命名zip文件文件夹

Python 解压缩并重命名zip文件文件夹,python,zip,directory,extract,Python,Zip,Directory,Extract,我想在python中从zip文件中提取一个特定的文件夹,然后在原始文件名后重命名它 例如,我有一个名为test.zip的文件,其中包含几个文件夹和子文件夹: xl/media/image1.png xl/drawings/stuff.png stuff/otherstuff.png 我想将媒体文件夹的内容提取到名为test的文件夹中: test/image1.png使用 模块,尤其是 从字符串test1.zip 创建临时目录的步骤 移动整个目录树 例如: #!/usr/bin/env p

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

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

xl/media/image1.png
xl/drawings/stuff.png
stuff/otherstuff.png
我想将媒体文件夹的内容提取到名为test的文件夹中:
test/image1.png

使用

  • 模块,尤其是
  • 从字符串
    test1.zip
  • 创建临时目录的步骤
  • 移动整个目录树
例如:

#!/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)
使用块处理创建目录、删除文件和提取zip文件时可能发生的各种异常。

使用

  • 模块,尤其是
  • 从字符串
    test1.zip
  • 创建临时目录的步骤
  • 移动整个目录树
例如:

#!/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)

使用块来处理创建目录、删除文件和提取zip文件时可能发生的各种异常。

样板问题:到目前为止您尝试了什么?例句问题:到目前为止你都做了些什么?如果有,请在问题中提及它。谢谢,当我指定zip_name='test.zip'时,这会起作用,但是使用sys.argv[1]时,我会得到一个错误:列表索引超出范围请参见文件顶部的用法。您应该将zip文件名作为命令行上的第一个参数(本例中)。如果您不想使用它,请将其更改为从任何需要的位置获取文件名。谢谢,当我指定zip_name='test.zip'时,这会起作用,但使用sys.argv[1]时,我会遇到一个错误:列表索引超出范围请参见文件顶部的用法。您应该将zip文件名作为命令行上的第一个参数(本例中)。如果这不是您想要使用它的方式,请更改它以从任何需要的地方获取文件名。