dkoug Blog

Create backup with python 3

Python -- Posted on Dec. 26, 2018

Create backup with python 3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import os
import datetime
import subprocess
from pathlib import Path

# list of folder names to backup 
folders = []

home = str(Path.home())
now = datetime.datetime.now()
year = now.year
day = now.day
month = now.month
d = "{}_{}_{}".format(year, day, month)
for folder in folders:
    exists = os.path.exists("{}/{}".format(home, folder))
    if exists:
        f = "{}/{}".format(home, folder)
        z = "{}_{}.tar.gz".format(folder, d)
        out = subprocess.Popen(
            ['tar', '--exclude', '{}/env'.format(folder),
             '{}/virtualenv'.format(folder),
             '{}/bower_components'.format(folder), '-zcvf', z, folder],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT)
        stdout, stderr = out.communicate()
        archive_exists = os.path.exists("{}/{}".format(home, z))
        if archive_exists:
            print('archive {} created '.format(z))