python 将数据从提供的位置备份到另一个位置的压缩文件。解决方案改编自使用Python自动化无聊的东西。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 将数据从提供的位置备份到另一个位置的压缩文件。解决方案改编自使用Python自动化无聊的东西。相关的知识,希望对你有一定的参考价值。

#! python2
# MyBackupScript.py - backup the My Documents folder and all contents into
# a zip file whole filename increments

import zipfile, shutil, os, sys

#function to create the backup zip file
def backupToZip(folder, location):
    # Backup the entire contents of "folder" into a zip file
    
    folder = os.path.abspath(folder) #make certain the path is an abs one

    # figure out the filename this code should use based on what files
    # already exist in location
    number = 1
    while True:
        zipFilename = location + os.path.basename(folder) + '_' + str(number) + '.zip'
        if not os.path.exists(zipFilename):
            break
        number = number + 1

    # set the filename
    zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
    
    # Create the zip file
    print('Creating %s...' % (zipFilename))
    backupZip = zipfile.ZipFile(zipFilename, 'w')

    # Walk the entire folder tree and compress the files in each folder
    for foldername, subfolders, filenames in os.walk(folder):
        print('Adding files in %s...' % (foldername))
        # Add the current folder to the zip file
        backupZip.write(foldername)
        # Add all the files in this folder to the zip file
        for filename in filenames:
            newBase = os.path.basename(folder) + '_'
            if filename.startswith(newBase) and filename.endswith('.zip'):
                continue # don't backup the backup zip files
            backupZip.write(os.path.join(foldername, filename))
    backupZip.close()
    #move the file from the directory copied to given location
    shutil.move(zipFilename, (location + zipFilename))
    print('Done.')

# The Main body of the program; call the function backupToZip
if len(sys.argv) != 3:
    print('Usage: py.exe MyBackupScript.py Dir_to_Copy Location_to_Store')
    sys.exit()
    
backupToZip(sys.argv[1], sys.argv[2])

以上是关于python 将数据从提供的位置备份到另一个位置的压缩文件。解决方案改编自使用Python自动化无聊的东西。的主要内容,如果未能解决你的问题,请参考以下文章

将 .bak 数据库文件从备份位置移动到另一台服务器

如何将 chrome 书签从单个桌面上的不同用户配置文件复制到另一个网络位置

Linux中rsync备份数据使用实例

Linux 中 rsync 备份数据使用实例

Linux 中 rsync 备份数据使用实例

如何将当前位置从一项活动发送到另一项活动?