【问题标题】:Python: Extract using tarfile but ignoring directoriesPython:使用 tarfile 提取但忽略目录
【发布时间】:2011-12-06 19:48:13
【问题描述】:

如果我有一个带有文件'/path/to/file.txt' 的 .tar 文件,有没有办法(在 Python 中)将文件提取到指定目录而不重新创建目录 '/path/to'

【问题讨论】:

    标签: python tar


    【解决方案1】:

    我也遇到这个问题,根据ekhumoro的回答列出完整的例子

    import os, tarfile
    output_dir = "."
    tar = tarfile.open(tar_file)
    for member in tar.getmembers():
      if member.isreg():  # skip if the TarInfo is not files
        member.name = os.path.basename(member.name) # remove the path by reset it
        tar.extract(member,output_dir) # extract 
    

    【讨论】:

      【解决方案2】:

      TarInfo 对象的数据属性是可写的。因此,只需将 name 更改为您想要的任何内容,然后提取它:

      import sys, os, tarfile
      
      args = sys.argv[1:]
      tar = tarfile.open(args[0])
      member = tar.getmember(args[1])
      member.name = os.path.basename(member.name)
      path = args[2] if len(args) > 2 else ''
      tar.extract(member, path)
      

      【讨论】:

      【解决方案3】:

      根据 tarfile 模块,您可以轻松做到这一点。 我还没看呢。

      TarFile.extract(member, path="")
      

      文档:

      使用其全名从存档中提取成员到当前工作目录。尽可能准确地提取其文件信息。 member 可以是文件名或 TarInfo 对象。您可以使用路径指定不同的目录。

      所以你应该可以做到

      TarFile.extract(member, path=".")
      

      查看完整文档:http://docs.python.org/library/tarfile.html

      【讨论】:

      • 当文档说“到当前工作目录,使用它的全名”时,“全名”实际上是一个路径。他们可能更准确地说“使用其完整路径,从当前工作目录开始......您可以使用路径指定不同的起始目录。”所以这个答案是行不通的。 ekhumoro 的回答似乎更好。
      【解决方案4】:

      您可以使用TarFile.extractfile(member) 来提取特定文件。

      它返回一个类似文件的对象(典型的 Python),然后您可以使用该对象将内容写入您想要的任何位置的文件中。

      【讨论】:

      • 这可行,但它不会保留文件元数据(修改时间等)。
      【解决方案5】:

      如果您只需要某些类型的文件(如 .xml 或 .html),您可以检查 item.name.endswith('xml')。 只是为了匹配前面的例子:

      import os, tarfile
      tarfilename = <your_tar_file>
      exitfolder = "." #your path
      
      tar = tarfile.open(tar_file, 'r:*') # open a .tar.gz file i.e.
      for item in tar:
        if item.name.endswith('xml'):  # getting only xml extensions
          item.name = os.path.basename(item.name) # remove the path
          tar.extract(item,exitfolder) # extract 
      

      【讨论】:

      • 使用tarfile.open(tar_file, 'r:*')接受所有压缩格式
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多