Search code examples
pythonpython-2.xtarfile

tarfile.open() does not extract into the right directory path


I'm trying to extract all from a tar.gz file into the same Directory. The following code works to extract all, but the files are stored in the working directory instead of the path I entered as name.

import tarfile
zip_rw_data = r"P:\Lehmann\Test_Python_Project\RW_data.tar.gz"
tar = tarfile.open(name=zip_rw_data, mode='r')
tar.extractall()
tar.close()

How do I make sure the extracted files are saved in the directory path where I need them? I've been trying at this for ages, I really can't see why this doesn't work.


Solution

  • You should use:

    import tarfile
    zip_rw_data = r"P:\Lehmann\Test_Python_Project\RW_data.tar.gz"
    tar = tarfile.open(name=zip_rw_data, mode='r')
    tar.extractall(path=r"P:\Lehmann\Test_Python_Project")
    tar.close()