The Wayback Machine - https://web.archive.org/web/20240530113728/https://www.geeksforgeeks.org/automate-backup-with-python-script/
Open In App

Automate backup with Python Script

Last Updated : 31 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Stepwise Implementation:

Step 1:  Import the following modules

Python3




import shutil
from datetime import date
import os
import 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)

Below is the full implementation:

Python3




# Import the following modules
import shutil
from datetime import date
import os
import sys
  
# When there is need, just change the directory
os.chdir(sys.path[0])  
  
# Function for performing the
# backup of the files and folders
def 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 function
take_backup("GFG.txt")


Output:

Folders BackUp:



Previous Article
Next Article

Similar Reads

Python Script to Automate Refreshing an Excel Spreadsheet
In this article, we will learn how we can automate refreshing an Excel Spreadsheet using Python. So to open the Excel application and workbooks we are going to use the pywin32 module. You can install the module using the below code: pip install pywin32 Then we are going to open the Excel application using the win32com.client.Dispatch() method and w
1 min read
Python Script to Automate Software Installation
Software installation can often be a time-consuming and monotonous undertaking, particularly when dealing with multiple applications. Python scripting gives a solution by enabling automation of the entire installation process which leads to more time consuming, enhances productivity, and gets rid of repetitive manual intervention. So, let's dive in
4 min read
How to Create a Backup of a SQLite Database using Python?
In this article, we will learn How to Create a Backup of an SQLite Database using Python. To Create a Backup of an SQLite Database using Python, the required modules are SQLite3 and IO. First, let's create the original database to do that follow the below program: C/C++ Code import sqlite3 import io from sqlite3 import Error def SQLite_connection()
2 min read
How to take backup of MySQL database using Python?
In this article, we are going to learn how to back up a MySQL database using python. Database used: Python modules required: In this post, we are going to use the mysql-connector module of python to back up our data. You can install mysql-connector with the following command: pip install mysql-connectorBacking Up Database: So, it's a fairly simple
3 min read
Python | Automate Google Search using Selenium
Google search can be automated using Python script in just 2 minutes. This can be done using selenium (a browser automation tool). Selenium is a portable framework for testing web applications. It can automatically perform the same interactions that any you need to perform manually and this is a small example of it. Mastering Selenium will help you
3 min read
Automate linkedin connections using Python
LinkedIn connections are a very important thing for an IT professional, so we need to send connection requests to a lot of people who can be useful to us. But sometimes sending connection requests one at a time can be a little annoying and hectic. It would be nice to automate this work but How? Python to rescue!In this article, we will learn how to
3 min read
Automate getter-setter generator for Java using Python
Encapsulation is defined as the wrapping up of data under a single unit. Encapsulation can be achieved by declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables. These public methods are called getters and setters. In practice, it is quite a time consuming and repetitive pr
3 min read
Automate Instagram Messages using Python
In this article, we will see how to send a single message to any number of people. We just have to provide a list of users. We will use selenium for this task. Packages neededSelenium: It is an open-source tool that automates web browsers. It provides a single interface that lets you write test scripts in programming languages like Ruby, Java, Node
6 min read
How to Automate VPN to change IP location on Ubuntu using Python?
To Protect Our system from unauthorized users Access you can spoof our system's IP Address using VPN service provided by different organizations. You can set up a VPN on your system for free. After you set up and log in to the VPN over the Ubuntu system you need to manually connect with different VPN servers after some duration. We can automate it
3 min read
How to Automate an Excel Sheet in Python?
Before you read this article and learn automation in Python....let's watch a video of Christian Genco (a talented programmer and an entrepreneur) explaining the importance of coding by taking the example of automation. You might have laughed loudly after watching this video and you surely, you might have understood the importance of automation in r
8 min read
Article Tags :
Practice Tags :