【问题标题】:Extract contents of folder in tar file提取tar文件中文件夹的内容
【发布时间】:2018-11-15 12:09:26
【问题描述】:

我正在尝试在 python 中提取 tar 文件,并且想知道是否可以在 tar 文件中提取文件夹的内容。 例如:

tar_files.tar.gz

  • tar_files
    • test.txt
    • test2.txt
    • 我的目录
      • test3.txt
    • mydir2
      • test4.txt

我想把它解压到mydirectory,像这样:

  • 我的目录
    • test.txt
    • test2.txt
    • 我的目录
      • test3.txt
    • mydir2
      • test4.txt

我应该如何解决这个问题?

【问题讨论】:

  • 您查看过tarfile 模块吗?
  • 我正在使用tarfile 模块。但是,当我尝试提取文件时,它会使用mydirectory 下的tar_files 目录进行提取。相反,我想要tar_files 的内容,里面有mydirectory

标签: python tar


【解决方案1】:

这是一种快速而简单的方法:

import os
import sys

#Name of tarfile (without the .tar.gz extension)
file_name = "tarfile"

#Target directory
target_dir = "mydirectory"


#Extract the tar file
os.system("tar -xf " + file_name + ".tar.gz")

#Move the tar files into your target folder
os.system("mv " + file_name + " " + target_dir)

虽然os.system 调用可能不是最佳实践,但它可以快速完成工作。

您也可以查看tarfile 模块:https://docs.python.org/2/library/tarfile.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多