Skip to content

Instantly share code, notes, and snippets.

@dimkoug
Created June 22, 2019 10:42
Show Gist options
  • Save dimkoug/3c4aceddded98de735307cb814cef801 to your computer and use it in GitHub Desktop.
Save dimkoug/3c4aceddded98de735307cb814cef801 to your computer and use it in GitHub Desktop.
Python 3 script to tar multiple folders in one archive
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
dest = '/media/disk/00_projects/'
'''
folders is a list of folder paths to backup
for example
folders = [
'/var/www/',
'.ssh'
]
'''
folders = []
try:
if dest is not None:
os.makedirs(dest)
except OSError as e:
if e.errno == errno.EEXIST:
print('Directory not created.')
else:
raise
archived_name = "backup_{}.tar.gz".format(date_string)
print('create archive for folder :', archived_name)
out = subprocess.Popen(['tar', '-zcvf', archived_name] + folders,
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