In this article we will see how to extract the contents of a TAR file with Python.
We can use the core module tarfile
by specifying the path of the input TAR file and the directory where to extract the files contained in the archive.
import tarfile
def extract_files(input_file=None, dest_dir=None):
if input_file is None or dest_dir is None:
return False
try:
with tarfile.open(input_file, 'r') as tarf:
tarf.extractall(dest_dir)
return True
except (tarfile.TarError, EOFError):
return False
In this case we have to handle the main exceptions that could be raised during the TAR archive extraction process.