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()
Take a look at the TarFile.add
signature:
... If given,
arcname
specifies an alternative name for the file in the archive.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With