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

Ale*_*lex 37 python gzip unzip tar

我正在尝试制作一个脚本,用于从一个目录中的文件夹中解压缩所有.tar.gz文件.例如,我将调用一个文件(testing.tar.gz).然后如果我手动操作,我可以按"提取",然后.tar.gz文件将创建一个新文件,并调用testing.tar.最后,如果我重复按"提取此处"的过程,.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)
Run Code Online (Sandbox Code Playgroud)

Lye*_*Foo 74

当你可以轻松地执行一次时,为什么要"按"两次以提取.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()
Run Code Online (Sandbox Code Playgroud)

  • @Alex`fname`将是一个你的文件名字符串. (5认同)
  • @Matthew您可以在extractall()命令中使用path参数,例如`tar.extractall(path =“ / new / dir / location”)`。您也可以具有更多控制权,例如,如果您需要使用extract()仅提取tar文件中的几个文件。要获得更多控制,请查看手册页。https://docs.python.org/3/library/tarfile.html (2认同)

小智 9

如果您使用的是python 3,则应使用适用于大多数常见归档格式的shutil.unpack_archive

shutil.unpack_archive(filename [,extract_dir [,format]])

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

例如:

def extract_all(archives, extract_path):
    for filename in archives:
        shutil.unpack_archive(filename, extract_path)
Run Code Online (Sandbox Code Playgroud)

  • 无论如何,有没有办法控制提取的文件的名称。 (4认同)
  • 当用户没有 root 权限时,`tarfile` 无法运行,但 `shutil` 可以。 (3认同)

小智 6

使用上下文管理器:

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'])
Run Code Online (Sandbox Code Playgroud)