Daily backup script in Python

How to create daily backup in python ? Using shutil and date packages we can create a simple daily backup script.

# Author : Manoj Koyadan
# Purpose: Daily folder backup script 

# Operating System – Ubuntu 64-bit
# Python Version – 2.7.11

import shutil
from datetime import date

class backup:
def __init__(self):
self.backupday = date.today()
self.newfolder = self.backupday.strftime(“%B%d”)
self.fromfolder = “/home/hostname/work”
self.tofolder = “/home/hostname/backup/” + self.newfolder
self.backup()
print “Backup created as zip file at-“,self.tofolder

def backup(self):
shutil.copytree(self.fromfolder,self.tofolder) #copying
shutil.make_archive(self.tofolder,’zip’,self.tofolder) #zipping
shutil.rmtree(self.tofolder) #cleaning

if __name__ == “__main__”:
backup = backup()

Note that above program reads all files from a particular folder and copy to another backup folder after zipping it. You can customize it by choosing only particular file types. This script can be automated by calling from a shell script or control-m job. it will create new folder every day.

Below script is for windows. Only difference is file path

# Operating System – Windows 7 64-bit
# Python Version – 2.7.11

import shutil
from datetime import date

class backup:
def __init__(self):
self.backupday = date.today()
self.newfolder = self.backupday.strftime(“%B%d”)
self.fromfolder = “C:\\work”
self.tofolder = “C:\\backup\\” + self.newfolder
self.backup()
print “Backup created as zip file at-“,self.tofolder

def backup(self):
shutil.copytree(self.fromfolder,self.tofolder) #copying
shutil.make_archive(self.tofolder,’zip’,self.tofolder) #zipping
shutil.rmtree(self.tofolder) #cleaning

if __name__ == “__main__”:
backup = backup()

Note:- Above code may not work if you copy and paste exactly. Please format as per python interpreter ( or Use any python IDLE, I used Spyder)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s