使用Python tarfile模块解压缩tar.bz2文件

Jul*_*ien 0 python tarfile

我有很多扩展名为"tar.bz2"的文件,我想解压缩它们.所以我使用"tarfile"模块,如下所述:https://docs.python.org/3/library/tarfile.html.

我尝试以下代码:

import tarfile
tar = tarfile.open("path_to/test/sample.tar.bz2", "r:bz2")  
for i in tar:
  tar.extractall(i)
tar.close()
Run Code Online (Sandbox Code Playgroud)

但没有任何反应:tar.bz2文件尚未解压缩到文件夹"path_to/test /"中.

你有什么想法吗?
谢谢 !

kvo*_*iev 8

您使用带有错误参数的tar.extractall.我想,你需要这样的东西

import tarfile
tar = tarfile.open("path_to/test/sample.tar.bz2", "r:bz2")  
tar.extractall()
tar.close()
Run Code Online (Sandbox Code Playgroud)

要么

import tarfile
tar = tarfile.open("path_to/test/sample.tar.bz2", "r:bz2")  
for i in tar:
  tar.extractfile(i)
tar.close()
Run Code Online (Sandbox Code Playgroud)

如果需要将文件解压缩到某个特定文件夹

import tarfile
tar = tarfile.open("path_to/test/sample.tar.bz2", "r:bz2")  
tar.extractall(some_path)
tar.close()
Run Code Online (Sandbox Code Playgroud)


mja*_*mja 5

我喜欢上下文管理器:

import tarfile

def extract_bz2(filename, path="."):
    with tarfile.open(filename, "r:bz2") as tar:
        tar.extractall(path)
Run Code Online (Sandbox Code Playgroud)