Automate backup with Python Script - GeeksforGeeks

31 Aug, 2021
In this article, we are going to see how to automate backup with a Python script.
File backups are essential for preserving your data in local storage. We will use the shutil, os, and sys modules. In this case, the shutil module is used to copy data from one file to another, while the os and sys modules are used to obtain the directory path and so on.
Step 1:  Import the following modules
Python3
import shutilfrom datetime import dateimport osimport sys
Step 2: Let us now get today’s date using the datetime module.
Python3
today = date.today()date_format = today.strftime("%d_%b_%Y_")
Step 3: If the user specifies the path to the source file, use the line below to concatenate the path to the source file with the name of the source file.
Python3
src_dir = src_dir+src_file_name
If not, and your file is stored in the same directory as your current Python script, use the os module to determine the current path of the file and create the source directory by combining the path provided by the os module with the source file name.
Python3
os.chdir(sys.path[0])
Step 4: If the user does not specify the source file name, we must return a file does not exist error.
Python3
if not src_file_name:   print("Please give atleast the Source File Name")
Step 5: Now, use the following cases to test the necessary conditions.
If the user provides all of the inputs, such as the source file name, source file path, destination file name, and destination file path.
Python3
if src_file_name and dst_file_name and src_dir and dst_dir:     src_dir = src_dir+src_file_name     dst_dir = dst_dir+dst_file_name
If the destination file name is None, which indicates that the user did not specify a destination file name, then use the conditions listed below.
Python3
elif dst_file_name is None or not dst_file_name:       dst_file_name = src_file_name       dst_dir = dst_dir+date_format+dst_file_name
If a user enters an empty string with one or more spaces.
Python3
elif dst_file_name.isspace():      dst_file_name = src_file_name      dst_dir = dst_dir+date_format+dst_file_name
If the user inputs the backup copy’s name, just concatenate the destination directory, date, and destination file name to create the output file name.
Python3
else:      dst_dir = dst_dir+date_format+dst_file_name
Step 6: Finally, we simply need to use the shutil function to copy the file to the destination.
Python3
shutil.copy2(src_dir, dst_dir)
Note: If we want to back up the entire folder rather than individual files, we must use the code below.
shutil.copytree(src_file_name, dst_dir)
Python3
# Import the following modulesimport shutilfrom datetime import dateimport osimport sys  # When there is need, just change the directoryos.chdir(sys.path[0])    # Function for performing the# backup of the files and foldersdef take_backup(src_file_name,                 dst_file_name=None,                src_dir='',                 dst_dir=''):    try:                  # Extract the today's date        today = date.today()          date_format = today.strftime("%d_%b_%Y_")          # Make the source directory,        # where we wanna backup our files        src_dir = src_dir+src_file_name          # If user not enter any source file,        # then just give the error message...        if not src_file_name:            print("Please give atleast the Source File Name")            exit()          try:                        # If user provides all the inputs            if src_file_name and dst_file_name and src_dir and dst_dir:                src_dir = src_dir+src_file_name                dst_dir = dst_dir+dst_file_name                              # When User Enter Either             # 'None' or empty String ('')            elif dst_file_name is None or not dst_file_name:                dst_file_name = src_file_name                dst_dir = dst_dir+date_format+dst_file_name                              # When user Enter an empty            # string with one or more spaces (' ')            elif dst_file_name.isspace():                dst_file_name = src_file_name                dst_dir = dst_dir+date_format+dst_file_name                              # When user Enter an a            # name for the backup copy            else:                dst_dir = dst_dir+date_format+dst_file_name              # Now, just copy the files            # from source to destination            shutil.copy2(src_dir, dst_dir)              print("Backup Successful!")        except FileNotFoundError:            print("File does not exists!,\            please give the complete path")          # When we need to backup the folders only...    except PermissionError:          dst_dir = dst_dir+date_format+dst_file_name                  # Copy the whole folder        # from source to destination        shutil.copytree(src_file_name, dst_dir)  # Call the functiontake_backup("GFG.txt")
Output:
Folders BackUp:
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()