4

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

Mahakaal
  • 2,075
  • 9
  • 27
  • 38

2 Answers2

10

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()
amillerrhodes
  • 2,662
  • 1
  • 17
  • 19
  • thanks buddy , i will try that , will it work if i have many subdirectories and files . i mean i want to have separate backups for `/home/user1.tar.gz , /home/user2.tar.gz` – Mahakaal May 02 '11 at 06:06
1

python write string directly to tarfile and http://docs.python.org/library/tarfile.html#tar-examples

Community
  • 1
  • 1
tmg
  • 872
  • 6
  • 7
  • its not only string anmes but complete folders with 100s of files . how can i feed folder – Mahakaal May 01 '11 at 17:30
  • 1
    use os.walk() to walk into the the related folder and adding each file individually. –  May 01 '11 at 17:42