Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Python: Untar file and change directory to extracted folder

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 folder has same name as the tar.gz file but if there is a difference then throws me an error that it could not change the directory? How can I improve this code?

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

    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


        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]

1 Answer

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Hmm, I haven't ever tried this. You could use os.listdir() to get a list of all of the files and directories in the directory, then untar the file, then get the list again. Find the difference between them (set.difference() would work, I'd think), and then os.chdir into that new directory?