I meet this problem as well, and list the complete example based on ekhumoro's answer

import os, tarfile
output_dir = "."
tar = tarfile.open(tar_file)
for member in tar.getmembers():
  if member.isreg():  # skip if the TarInfo is not files
    member.name = os.path.basename(member.name) # remove the path by reset it
    tar.extract(member,output_dir) # extract 
Answer from Larry Cai on Stack Overflow
Discussions

Extract only a single directory from tar (in python) - Stack Overflow
Great tip. Having tarfile extracted with every useless subdirectory really bugged me. More on stackoverflow.com
๐ŸŒ stackoverflow.com
Python: Untar file and change directory to extracted folder
Abdus Samad is having issues with: How do I untar file in mac using python and change the working directory to the extracted folder? I wrote below code which works if untarred fol... More on teamtreehouse.com
๐ŸŒ teamtreehouse.com
1
February 15, 2017
python - Extract all files with directory path in given directory - Stack Overflow
You should probably change ... a directory. 2024-02-20T07:51:34.74Z+00:00 ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... Starting February 24, 2026: check out our new site design at... 84 How can files be added to a tarfile with Python, without adding the ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Extract file from directory inside tar file without creating that directory - Unix & Linux Stack Exchange
I have a tarfile which has the following structure: - dir1 -- file - dir2 - dir3 If I try running tar -xf tarfile.tar.gz dir1/file, dir1 containing the file will be created. I would like instead to More on unix.stackexchange.com
๐ŸŒ unix.stackexchange.com
September 26, 2016
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ How-are-files-extracted-from-a-tar-file-using-Python
How are files extracted from a tar file using Python?
May 28, 2025 - The extract() method in Python is used to extract a specific file from a TAR archive. This is useful when you don't want to extract the entire archive but only one particular file.
๐ŸŒ
Team Treehouse
teamtreehouse.com โ€บ community โ€บ python-untar-file-and-change-directory-to-extracted-folder
Python: Untar file and change directory to extracted folder (Example) | Treehouse Community
February 15, 2017 - import sys file = sys.argv[-1] # get user input import os dir = os.path.dirname(file) # get directory where file is stored filename = os.path.basename(file) # get filename file_tar, file_tar_ext = os.path.splitext(file) # split into file.tar and .gz file_untar, file_untar_ext = os.path.splitext(file_tar) #split into file and .tar os.chdir(dir) if file_tar_ext == ".gz" and file_untar_ext == ".tar": # check if file had format .tar.gz import tarfile tar = tarfile.open(filename) tar.extractall(path=dir) # untar file into same directory tar.close() os.chdir(file_untar) # This fails if file.tar.gz has different name compared to the untarred folder e.g.. file1 instead of file ยท Thanks Abdus ยท [MOD: added ```python formatting -cf] STAFF ยท
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ tarfile.extractall() processes fine but doesn't create any new files or directories
r/learnpython on Reddit: TarFile.extractall() processes fine but doesn't create any new files or directories
October 16, 2019 -

Version: Python 2.7

OS: MacOS Mojave

IDE: Pycharm Community 2019.2

I'm having trouble downloading tar.gz files from `pypi.org/project` and unzipping them. The use case for this is that we can't use any actual package management, so we have to manually put packages where we need them in the local folders. My solution to this is to read a requirements file and pull the tar.gz and .zip files for the given versions and then write to local files.

I've got it working for zip files, and it works exactly how I want it to. Zip files are handled by the 'elif' statement, tar files are handled by the 'if' statement. For some reason, for the tar file links I pass in, no directories are created, no files are extracted.

I did a test by putting the path to my local copy of a tar file directly in this line `tarData = tarfile.open(fileobj=zipData, mode='r:*')` instead of `zipData` and it worked, so I think it has something to do with the format the file is being either downloaded in or handled in StringIO, but I'm not getting any exceptions so I have no way to narrow down what the issue could be.

Below is the slice of code I'm using to unzip these files:

import os
import bs4 as bs
import urllib2
import re
from StringIO import StringIO
import zipfile
import tarfile
import requests


def install_packages_locally(compressed_link, directory):
    file_name = '_'.join(compressed_link.split('/')[-1].split('-')[:-1])
    file_ext = compressed_link.split('-')[-1]
    response = requests.get(compressed_link, stream=True)

    if file_name in os.listdir(directory):
        print('Skipping %s' % file_name)
        return True

    zipData = StringIO()

    if file_ext.endswith('.tar.gz'):
        zipData.write(response.raw.read())
        print('writing %s to %s' % (file_name, directory))
        tarData = tarfile.open(fileobj=zipData, mode='r:*')
        tarData.extractall(path='/dir/Packages')
        tarData.close()
        zipData.close()
        return True

    elif file_ext.endswith('.zip'):
        zipData.write(response.content)
        print('writing %s to %s' % (file_name, directory))
        unzipData = zipfile.ZipFile(zipData)
        unzipData.extractall(path='/dir/Packages/')
        unzipData.close()
        zipData.close()
        return True
๐ŸŒ
LinuxConfig
linuxconfig.org โ€บ home โ€บ how to create and manipulate tar archives using python
Use Tarfile Module in Python: A Complete Guide
June 3, 2020 - Another very common operation we may want to perform on a tar archive is to extract all its content. To perform such operation we can use the extractallmethod of the corresponding TarFile object.
๐ŸŒ
AskPython
askpython.com โ€บ home โ€บ the tarfile module โ€“ how to work with tar files in python?
The tarfile Module - How to work with tar files in Python? - AskPython
February 16, 2023 - The following code is an implementation for creating a tar file in Python. Here we use open() method for creating tar file and add() method for adding other files to a tar file. #import module import tarfile #declare filename filename= "tutorial.tar" #open file in write mode file_obj= tarfile.open(filename,"w") #Add other files to tar file file_obj.add("plane.xml") file_obj.add("sample.txt") file_obj.add("person.ini") #close file file_obj.close()
๐ŸŒ
CodeQL
codeql.github.com โ€บ codeql-query-help โ€บ python โ€บ py-tarslip
Arbitrary file write during tarfile extraction โ€” CodeQL query help documentation
In this example an archive is extracted without validating file paths. If archive.tar contained relative paths (for instance, if it were created by something like tar -cf archive.tar ../file.txt) then executing this code could write to locations outside the destination directory. import sys import tarfile with tarfile.open(sys.argv[1]) as tar: #BAD : This could write any file on the filesystem.
๐ŸŒ
Python Engineer
python-engineer.com โ€บ posts โ€บ tarfile-python
How to work with tarball/tar files in Python - Python Engineer
In order to selectively extract files, we need to pass a reference of the file object or file path as string to tarfile.TarFile.extract method.
๐ŸŒ
Python Module of the Week
pymotw.com โ€บ 2 โ€บ tarfile
tarfile โ€“ Tar archive access - Python Module of the Week
February 22, 2009 - import tarfile t = tarfile.open('example.tar', 'r') for filename in [ 'README.txt', 'notthere.txt' ]: try: f = t.extractfile(filename) except KeyError: print 'ERROR: Did not find %s in tar archive' % filename else: print filename, ':', f.read() $ python tarfile_extractfile.py README.txt : The examples for the tarfile module use this file and example.tar as data.
๐ŸŒ
Python
peps.python.org โ€บ pep-0706
PEP 706 โ€“ Filter for tarfile.extractall | peps.python.org
Python allows extracting tar archives using tarfile.TarFile.extractall(), whose docs warn to never extract archives from untrusted sources without prior inspection. However, itโ€™s not clear what kind of inspection should be done. Indeed, itโ€™s quite tricky to do such an inspection correctly.