在python中,如果提取一个tar.gz文件,如何获取或设置结果文件的名称

In python, if extract a tar.gz file, how to get or set the name of the result file

我的问题是: 使用时:

import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall()
tar.close()

如果压缩前的文件叫"sampleFolder",在我做了上面的步骤后,如何return "sampleFolder" 名称,最好是它的完整路径,或者如何设置结果为其他名称,例如 "Folder"?

这不是一个好问题,但我在我的项目中确实有这个需求。

我必须将问题编辑为:如果我不知道 "sampleFolder",我可以在解压步骤

后获得 return

默认解压到工作目录:

import os
os.getcwd()

所以,提取数据的路径是:

from pathlib import Path
extracted_to_path = Path.cwd() / 'sampleFolder'

要提取到不同的位置:

with tarfile.open('sample.tar.gz') as tar:
    tar.extractall(path='/other/folder')

编辑: 如果您只想知道存档中包含的名称 "sampleFolder",则没有必要提取到某个地方。你应该使用 getnames:

tar.getnames()

请注意,压缩包中可以包含多个文件或文件夹。

Python 提供 shutil 库,可以提取 zip 文件。

import shutil
help(shutil.unpack_archive)

unpack_archive(filename, extract_dir=None, format=None) Unpack an archive.

`filename` is the name of the archive.

`extract_dir` is the name of the target directory, where the archive
is unpacked. If not provided, the current working directory is used.

`format` is the archive format: one of "zip", "tar", "gztar", "bztar",
or "xztar".  Or any other registered format.  If not provided,
unpack_archive will use the filename extension and see if an unpacker
was registered for that extension.

In case none is found, a ValueError is raised.
shutil.unpack_archive(filename="file_path", extract_dir="path_where_you_want_extracted_file", format="tar/zip")