Chris
Chris

Reputation: 11

Python3 - how to write tarfile to a different directory?

I am trying to do a backup of directory in variable target_path to a file assigned in variable archive_name.tar.gz and write that file to a directory other than the current directory. The code below works but places the output in the current working directory. I can't work out whether there is a way of adding an argument to write the file to a directory specified in variable write_path. Any help appreciated!

with tarfile.open(archive_name+'.tar.gz', mode='w:gz') as archive:

archive.add(target_path, recursive=True)

Upvotes: 0

Views: 777

Answers (1)

Mathemagician
Mathemagician

Reputation: 461

You should do it in the open function. You can either use a relative path for example:

with tarfile.open('../test'+'.tar.gz', mode='w:gz') as archive:
    archive.add('test', recursive=True)

which makes the tar file in parnet folder or an absolute path like:

with tarfile.open('/home/user/Desktop/test'+'.tar.gz', mode='w:gz') as archive:
    archive.add('test', recursive=True)

Upvotes: 1

Related Questions