Created
June 22, 2019 10:41
-
-
Save dimkoug/3f31343c0e9c1d18c5ee2d19e7cf16a0 to your computer and use it in GitHub Desktop.
Python 3 script to tar multiple folders
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import datetime | |
import subprocess | |
import shutil | |
import errno | |
from pathlib import Path | |
home = str(Path.home()) | |
now = datetime.datetime.now() | |
year = now.year | |
day = now.day | |
month = now.month | |
date_string = "{}_{}_{}".format(year, day, month) | |
''' | |
dest var used to move created archives to another location | |
example : dest = '/media/disk/' | |
''' | |
dest = None | |
''' | |
folders is a list of folder paths to backup | |
for example | |
folders = [ | |
'/var/www/', | |
'.ssh' | |
] | |
''' | |
folders = [] | |
try: | |
os.makedirs(dest) | |
except OSError as e: | |
if e.errno == errno.EEXIST: | |
print('Directory not created.') | |
else: | |
raise | |
for folder in folders: | |
archived_name = None | |
exists = os.path.exists(folder) | |
if exists: | |
folder_path = folder | |
archived_name = "backup{}{}.tar.gz".format( | |
folder.replace('/', '_').replace('.', ''), date_string) | |
if archived_name: | |
if not os.path.exists(archived_name): | |
print('create archive for folder :', archived_name) | |
out = subprocess.Popen( | |
['tar', '--exclude', '{}/env'.format(folder), | |
'{}/virtualenv'.format(folder), | |
'{}/bower_components'.format( | |
folder), '-zcvf', archived_name, folder], | |
stdout=subprocess.PIPE, | |
stderr=subprocess.STDOUT) | |
stdout, stderr = out.communicate() | |
archive_exists = os.path.exists("{}/{}".format(home, archived_name)) | |
if archive_exists: | |
print('archive {} created '.format(archived_name)) | |
if dest: | |
if archived_name: | |
filename = "{}/{}".format(home, archived_name) | |
shutil.move(os.path.join( | |
home, archived_name), os.path.join(dest, archived_name)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment