Tarfile tar without full path

I made a small script, as shown below, to read a group of files and tar, all of its work is perfectly consistent with the fact that the compressed file contains the full path to the files when uncompressed. Is there a way to do this without a directory structure?

compressor = tarfile.open(PATH_TO_ARCHIVE + re.sub('[\s.:"-]+', '', 
    str(datetime.datetime.now())) + '.tar.gz', 'w:gz')

for file in os.listdir(os.path.join(settings.MEDIA_ROOT, PATH_CSS_DB_OUT)):
    compressor.add(os.path.join(settings.MEDIA_ROOT, PATH_CSS_DB_OUT) + file)

compressor.close()
+5
source share
2 answers

Take a look at the TarFile.addsignature:

... If specified, arcnameindicates an alternative file name in the archive.

+7
source

I created a context manager to change the current fo working directory handling this with tar files.

import contextlib
@contextlib.contextmanager
def cd_change(tmp_location):
    cd = os.getcwd()
    os.chdir(tmp_location)
    try:
        yield
    finally:
        os.chdir(cd)

Then, to pack everything in your case:

with cd_change(os.path.join(settings.MEDIA_ROOT, PATH_CSS_DB_OUT)):
    for file in os.listdir('.'):
        compressor.add(file)
+2
source

All Articles