📜  使用Python脚本自动备份

📅  最后修改于: 2022-05-13 01:55:43.210000             🧑  作者: Mango

使用Python脚本自动备份

在本文中,我们将了解如何使用Python脚本自动备份。

文件备份对于将数据保存在本地存储中至关重要。我们将使用shutilossys模块。在这种情况下,shutil 模块用于将数据从一个文件复制到另一个文件,而 os 和 sys 模块用于获取目录路径等。

分步实施:

第一步:导入以下模块

Python3
import shutil
from datetime import date
import os
import sys


Python3
today = date.today()
date_format = today.strftime("%d_%b_%Y_")


Python3
src_dir = src_dir+src_file_name


Python3
os.chdir(sys.path[0])


Python3
if not src_file_name:
   print("Please give atleast the Source File Name")


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


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


Python3
elif dst_file_name.isspace():
      dst_file_name = src_file_name
      dst_dir = dst_dir+date_format+dst_file_name


Python3
else:
      dst_dir = dst_dir+date_format+dst_file_name


Python3
shutil.copy2(src_dir, dst_dir)


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")


第 2 步:现在让我们使用 datetime 模块获取今天的日期。



蟒蛇3

today = date.today()
date_format = today.strftime("%d_%b_%Y_")

第 3 步:如果用户指定了源文件的路径,请使用下面的行将源文件的路径与源文件的名称连接起来。

蟒蛇3

src_dir = src_dir+src_file_name

如果没有,并且您的文件与您当前的Python脚本存储在同一目录中,请使用 os 模块确定文件的当前路径,并通过将 os 模块提供的路径与源文件名组合来创建源目录。

蟒蛇3

os.chdir(sys.path[0])

第四步:如果用户没有指定源文件名,就要返回文件不存在的错误。

蟒蛇3

if not src_file_name:
   print("Please give atleast the Source File Name")

第 5 步:现在,使用以下案例来测试必要条件。



如果用户提供了所有输入,例如源文件名源文件路径目标文件名目标文件路径

蟒蛇3

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

如果目标文件名是 None,表示用户没有指定目标文件名,则使用下面列出的条件。

蟒蛇3

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

如果用户输入一个带有一个或多个空格的空字符串。

蟒蛇3

elif dst_file_name.isspace():
      dst_file_name = src_file_name
      dst_dir = dst_dir+date_format+dst_file_name

如果用户输入备份副本的名称,只需连接目标目录日期目标文件名即可创建输出文件名。

蟒蛇3

else:
      dst_dir = dst_dir+date_format+dst_file_name

第 6 步:最后,我们只需要使用shutil函数将文件复制到目的地。

蟒蛇3



shutil.copy2(src_dir, dst_dir)

注意:如果我们要备份整个文件夹而不是单个文件,我们必须使用下面的代码。

shutil.copytree(src_file_name, dst_dir)

下面是完整的实现:

蟒蛇3

# 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")

输出:

文件夹备份: