Mahakaal
Mahakaal

Reputation: 2165

How to make tar backup using python

I have directory /home/user1 , user2 . I want to loop through all usernames home dir and then make the tar.gz file and then store it in /backups directory.

I am new to python so confused how to start

Upvotes: 4

Views: 4386

Answers (2)

amillerrhodes
amillerrhodes

Reputation: 2702

This should work:

import os
import tarfile

home = '/home/'
backup_dir = '/backup/'

home_dirs = [ name for name in os.listdir(home) if os.path.isdir(os.path.join(home, name)) ]

for directory in home_dirs:
    full_dir = os.path.join(home, directory)
    tar = tarfile.open(os.path.join(backup_dir, directory+'.tar.gz'), 'w:gz')
    tar.add(full_dir)
    tar.close()

Upvotes: 10

Related Questions