python - 如何使用 gpython 脚本从 sample.tar.gz 文件中提取选定的文件

标签 python python-3.x

我想从 sample.tar.gz 文件中提取一些选定的文件(不需要提取 sample.tar.gz 文件中的所有文件)文件结构如下所示。

sample.tar.gz is the base file, under this base file following files are contained.
 hello_usb.tar.gz
 hello_usb1.tar.gz
 hello_usb2.tar.gz
 world_usb1.tar.gz
 world_usb2.tar.gz
 world_usb3.tar.gz

我只想提取要提取的“hello_*”文件(例如,提取时应创建一个与文件名相同的文件夹名称,而提取 hello_usb.tar.gz 文件时应创建一个名为 as 的文件夹名称你好_usb.tar.gz/... )

我尝试了以下代码,但没有成功。

tar = tarfile.open("D:\Python34\Testing\sample.tar.gz", "r:gz")
only_names = tar.getnames()
for count in range(len(only_names)):
   print (only_names[count][:9])
   if only_names[count][:9] == "hello_usb":
      tar.extract(only_names[count], path = "D:\Python34\Testing")
      #tar.extractfile(only_names[count])

非常感谢您的帮助

最佳答案

这样的事情可能会奏效。

import shutil
import glob
import os

with tarfile.open('D:\Python34\Testing\sample.tar.gz', 'r:gz') as tar:
    tar.extractall()
    os.chdir('sample')
    for arch in glob.glob('hello_*'):
        shutil.unpack_archive(arch, 'D:\Python34\Testing')

关于python - 如何使用 gpython 脚本从 sample.tar.gz 文件中提取选定的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29484268/

相关文章:

python - 遍历列表列表并使用迭代器

python - 为什么有时会保持既定秩序?

python - 在Python中调用GDL脚本

python - "can' t 在编码的 urlopen 请求上将字节连接到 str"

Python 公共(public)假期在工作日

python - 将 numpy 数组转换为 rgb 图像

python - 我需要使用 xlwt 在其他行之间插入一行

python-3.x - 推荐使用 pydbus 或 dbus-python,有什么区别?

python - 如何在虚拟环境中安装模块

python - 为什么我的 equal 方法总是返回 false?