how to make a tar file backup of a directory in python
11,367
The good news is that tarfile
supports recursively adding members any work.
with tarfile.open(archive_name + '.tar.gz', mode='w:gz') as archive:
archive.add('/Users/localuser/Downloads/backup', recursive=True)
recursive=True
is the default, so you can omit it.
Author by
CodeTalk
Updated on July 30, 2022Comments
-
CodeTalk almost 2 years
What I'm trying to do: I'm trying to make a recursive
.tar
file backup of the directory this python script is run in.What I currently have:
import os import zipfile import datetime import tarfile datetime = str( datetime.datetime.now() ) def zipdir(path, zip): for root, dirs, files in os.walk(path): for file in files: zip.write(os.path.join(root, file)) backupdir = raw_input('Which directory should we backup to? \n') if backupdir : try: zipf = zipfile.ZipFile('DrupalInstanceBackup'+datetime+'.zip', mode='w') zipdir('/Users/localuser/Downloads/backup', zipf) except Exception as e: print e finally: zipf.close()
What it currently does: It makes a .zip backup, but when extracted it doesn't show any files.
What Im trying to do: Can someone help me make this script recursively backup a directory and create a
.tar
archive of the directory and its files in a recursive manner?Thank you
-
CodeTalk over 9 yearsDoes this tar the files of the directory the script is in?
-
kalhartt over 9 yearsI think you figured it out, but it will tar files of directories you add with
archive.add
. -
sagarr over 5 yearsIf you want to put all files from source dir without maintaining the complete dir structure, then you can pass
arcname=''