首页 > 解决方案 > 如何使用python解压缩和解压?

问题描述

所以我需要访问压缩文件夹(也是tar)中的文件和文件夹。用户提供此 Gunzip 文件所在的路径,从 python 代码中,我需要将所有这些文件解压缩、解压缩并将其提取到同一位置,然后访问此目录中的文件和文件夹。

path given by user - C:/Users/user1/Desktop/tar_gz/tarball.tar.xz

文件应解压缩到同一目录 - C:/Users/user1/Desktop/tar_gz/tarball

我是机器学习概念的新手,很难弄清楚这一点。有什么方法可以做到这一点吗?

标签: pythonextracttargunzip

解决方案


Python tarfile 模块

import tarfile
import os

path_tofile = r"C:/Users/user1/Desktop/tar_gz/tarball.tar.xz"
extract_direcotry = os.path.dirname(path_tofile)

if tarfile.is_tarfile(path_tofile):
    with tarfile.open(path_tofile) as f:
        f.extractall(path=extract_direcotry)  # Extract all members from the archive to the current working directory

推荐阅读