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

STR picture STR · Aug 30, 2017 · Viewed 9.2k times · Source

My question is like: when use:

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

if the file before compress called "sampleFolder", after I doing the above steps, how to return the "sampleFolder" name, better with its full path, or how to set the result to other name like "Folder"?

it's not a good question, but I actually have demand on this in my project.

I have to edit the question to: if I don't know the "sampleFolder", can I get a return to it after the decompress step

Answer

wim picture wim · Aug 30, 2017

It will be extracted to the working directory by default:

import os
os.getcwd()

So, the path to the extracted data is:

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

To extract in a different location:

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

edit: If you just want to know the name "sampleFolder" contained in the archive, it's not necessary to extract somewhere. You should use getnames:

tar.getnames()

Note that tarballs can have multiple files or folders within.