Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我想通过(Python)为解压(.tar.gz)文件创建一个脚本_Python_Tar_Unzip_Gzip - Fatal编程技术网

我想通过(Python)为解压(.tar.gz)文件创建一个脚本

我想通过(Python)为解压(.tar.gz)文件创建一个脚本,python,tar,unzip,gzip,Python,Tar,Unzip,Gzip,我正在尝试制作一个脚本,用于从一个目录中的文件夹中解压缩所有.tar.gz文件。例如,我将有一个它调用的文件(testing.tar.gz)。然后,如果我手动执行,我可以按“extract here”,然后.tar.gz文件将创建一个新文件,它将调用testing.tar。最后,如果我重复按“extract here”的过程,.tar文件将生成所有的.pdf文件 我想知道我该怎么做,我这里有我的代码,但它似乎不起作用 import os import tarfile import zipfile

我正在尝试制作一个脚本,用于从一个目录中的文件夹中解压缩所有.tar.gz文件。例如,我将有一个它调用的文件(testing.tar.gz)。然后,如果我手动执行,我可以按“extract here”,然后.tar.gz文件将创建一个新文件,它将调用testing.tar。最后,如果我重复按“extract here”的过程,.tar文件将生成所有的.pdf文件

我想知道我该怎么做,我这里有我的代码,但它似乎不起作用

import os
import tarfile
import zipfile

def extract_file(path, to_directory='.'):
    if path.endswith('.zip'):
        opener, mode = zipfile.ZipFile, 'r'
    elif path.endswith('.tar.gz') or path.endswith('.tgz'):
        opener, mode = tarfile.open, 'r:gz'
    elif path.endswith('.tar.bz2') or path.endswith('.tbz'):
        opener, mode = tarfile.open, 'r:bz2'
    else: 
        raise ValueError, "Could not extract `%s` as no appropriate extractor is found" % path

    cwd = os.getcwd()
    os.chdir(to_directory)

    try:
        file = opener(path, mode)
        try: file.extractall()
        finally: file.close()
    finally:
        os.chdir(cwd)
为什么要“按”两次以提取.tar.gz,而您可以轻松地执行一次?下面是一个简单的代码,可以一次性提取.tar和.tar.gz:

import tarfile

if fname.endswith("tar.gz"):
    tar = tarfile.open(fname, "r:gz")
    tar.extractall()
    tar.close()
elif fname.endswith("tar"):
    tar = tarfile.open(fname, "r:")
    tar.extractall()
    tar.close()

当我运行您的程序时,它对tar.gz和.tgz文件非常有效,当我打开zip时,它没有给我正确的项目,但是.tbz是唯一一个引发错误的项目。我认为您使用了错误的方法来解包.tbz,因为错误表明我的文件类型不正确,但我没有。解决.zip问题的一种方法是使用us os.command()并使用命令行(取决于您的操作系统)将其解压缩,因为它返回了一个_MACOSX文件夹,其中没有任何内容,即使我正确输入了路径。我遇到的另一个错误是,您使用了不正确的语法来引发错误。
这是您应该使用的:

raise ValueError("Error message here")

你用了逗号,没有括号。希望这有帮助

您可以使用以下命令从Python执行shell脚本:

import envoy # pip install envoy

if (file.endswith("tar.gz")):
    envoy.run("tar xzf %s -C %s" % (file, to_directory))

elif (file.endswith("tar")):
    envoy.run("tar xf %s -C %s" % (file, to_directory))

如果您使用的是Python3,那么应该使用它来处理大多数常见的归档格式

解包存档(文件名[,解压目录[,格式]])

打开档案。filename是归档文件的完整路径。 extract_dir是解压缩归档文件的目标目录的名称。如果未提供,则使用当前工作目录

例如:

def extract_all(archives, extract_path):
    for filename in archives:
        shutil.unpack_archive(filename, extract_path)
使用上下文管理器:

import tarfile
<another code>
with tarfile.open(os.path.join(os.environ['BACKUP_DIR'],
                  f'Backup_{self.batch_id}.tar.gz'), "r:gz") as so:
    so.extractall(path=os.environ['BACKUP_DIR'])
导入文件
使用tarfile.open(os.path.join(os.environ['BACKUP_DIR']),将,
f'Backup{self.batch{u id}.tar.gz'),“r:gz”)如下:
so.extractall(path=os.environ['BACKUP\u DIR'])

如果您在
jupyter笔记本
linux
机器中使用python,请执行以下操作:

!tar -xvzf /path/to/file.tar.gz -C /path/to/save_directory

允许在终端中运行命令。

除非使用Python有意义,否则它听起来像是最适合shell脚本的作业。extractall将目标目录作为参数,不需要chdir back,forthIt是因为,看起来像我拥有的文件(.tar.gz)。但是解压过程,它必须从(.tar.gz)提取到(.gz),然后,再次提取将给出我需要的信息,如.pdf文件etc,并且您的代码不起作用:if(fname.endswith(“tar.gz”)):name错误:名称“fname”不正确defined@Alex
fname
将是一个作为您的文件名的字符串。@Alex fname是您试图取消tar的文件名的字符串
files=[f代表os.listdir('.')中的f,如果os.path.isfile(f)]代表文件中的fname:#做点什么,例如上面的“if elif”代码。
@Matthew您可以在extractall()命令中使用path参数,例如
tar.extractall(path=“/new/dir/location”)
。您也可以拥有更多的控制权,例如,如果您只需要使用extract()提取tar文件中的几个文件。要获得更多控制,请查看手册页。是否仍然可以控制提取文件的名称。当用户没有root权限时,
tarfile
无法运行,但
shutil
可以运行。找到一行python代码,以最小的麻烦完成我需要的工作,激发了喜悦-谢谢!我预测python将是最后一种编程语言。@suraj subramanian,提取路径将包含新名称。例如,如果文件名是“hello.tar.gz”,则提取路径可能是“/tmp/my\u name\u here”