Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make a tar file backup of a directory in python

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

like image 664
CodeTalk Avatar asked Jan 27 '15 17:01

CodeTalk


1 Answers

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.

like image 103
kalhartt Avatar answered Sep 22 '22 16:09

kalhartt