简体   繁体   English

如何使用 python 进行 tar 备份

[英]How to make tar backup using python

I have directory /home/user1, user2.我有目录/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.我想遍历所有用户名的主目录,然后制作 tar.gz 文件,然后将其存储在 /backups 目录中。

I am new to python so confused how to start我是 python 的新手,很困惑如何开始

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM