How to make tar backup using python

会有一股神秘感。 提交于 2019-12-30 07:05:10

问题


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


回答1:


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()



回答2:


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



来源:https://stackoverflow.com/questions/5849999/how-to-make-tar-backup-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!