Get folder name of unzipped .tar.gz file

Viewed 396

I've got a python script that extracts everything from a .tar.gz file and then works on the extracted files.

The python code that extracts the item is currently:

    tar = tarfile.open(input_file)
    tar.extractall(output_location)
    tar.close()

Where input file is the tarball, and output_location is the folder to which I'm extracting the tarball.

The tarball is created via tar -czf (output filename) (input folder) , so the compressed materials are thus guaranteed to be inside a folder, and the only top-level item in the tarball will be that one folder. (The output location is not necessarily empty.) Normally, the extracted folder is named course, but it could theoretically be named anything.

Is there a way to get the name of that top-level folder, either before or after it's extracted?

Failing that, it's ok for me to rename the folder. Is there a way to extract all the compressed stuff inside the tarball's top-level folder so that I can put it in a folder I name myself? I could unzip everything into a new folder and then pull everything down one level of hierarchy, and that would be equivalent, but it feels like shooting a gnat with a cannon.

1 Answers

You can use os.listdir. In your case, a list with a single item is returned, the item being the name of the directory you need.

import os
dir_name = os.listdir(output_folder)[0]

or like this, which raises unless you have a single entry as expected:

dir_name, = os.listdir(output_folder)

EDIT

To simply get the names of the files/directories in the archive, use tar.getnames(). If you know you only have one, get it using tar.getnames()[0].

Related