Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python tarfile without full path

Tags:

python

django

tar

I made a small script as below to read group of files and tar them, its all working fine accept that the compressed file contain full path of the files when uncompressed. Is there a way to do it without the 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()
like image 698
Mo J. Mughrabi Avatar asked Jan 20 '11 18:01

Mo J. Mughrabi


2 Answers

Take a look at the TarFile.add signature:

... If given, arcname specifies an alternative name for the file in the archive.

like image 168
miku Avatar answered Oct 11 '22 13:10

miku


I created a context manager for changing the current working directory fo 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 package everything up in your case:

with cd_change(os.path.join(settings.MEDIA_ROOT, PATH_CSS_DB_OUT)):
    for file in os.listdir('.'):
        compressor.add(file)
like image 31
Grant Limberg Avatar answered Oct 11 '22 14:10

Grant Limberg