备份脚本不会遍历文件夹中的文件

时间:2018-11-23 14:06:43

标签: python zipfile

我是Python的新手,我的第一个项目之一是制作备份脚本。

该脚本会创建一个zip文件,其中包含文件夹的名称和一个数字,每次执行时都会增加。

但是该脚本似乎仅创建zip文件,但未添加任何文件。

import zipfile, os
def backupToZip(folder):
    # Backup the entire contents of "folder" into a ZIP file.
    folder = os.path.abspath(folder) # make sure folder is absolute
    # Figure out the filename this code should use based on
    # what files already exist.
    number = 1
    while True:
        zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
        if not os.path.exists(zipFilename):
            break
        number = number + 1
    # TODO: Create the ZIP file.
    print('Creating %s...' % (zipFilename))
    backupZip = zipfile.ZipFile(zipFilename, 'w')
    # TODO: 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()
    print('Done.')

backupToZip('C:\\Users\xe76572\\Downloads\\carpetaWindows')

我正在尝试备份具有以下结构的文件夹: carpetaWindows。

  • text1.txt
  • text2.txt
  • text3.txt

0 个答案:

没有答案