备份一棵文件夹树,但单独打印每个文件

时间:2018-12-14 18:55:25

标签: python python-3.x tarfile

我正在创建一个脚本来备份具有多个文件夹,数据库以及数百个文件夹和文件的整个程序。为此,我使用了这段代码,并且效果很好(为SO稍作修改)。

import tarfile
import datetime
PATH_PROGRAM = os.getcwd()

# Part 1: Get list of files
files_to_save = []
for file_name in listdir(PATH_PROGRAM):
    if not file_name == "Backups Folder": # Exclude the folder where we store them
        files_to_save.append(file_name)

# Part 2: Get name for new backup file
date_now = str(datetime.datetime.now())[:10]
backupfile = "{0}\\Backups Folder\\{1}.tar.gz".format(PATH_PROGRAM, date_now)

# Part 3: Add all files to new backup
with tarfile.open(backupfile, "w:gz") as tar:
    for file in files_to_save:
        print("Saving: {0}".format(file))
        tar.add("{0}\\{1}".format(PATH_PROGRAM, file))

问题:
使用此代码,我的照片只会显示基本文件夹,而不是每个文件,例如:

Saving: File1.txt
Saving: File2.mp3
Saving: Folder_sounds
Saving: something.json

让我们假装folder_sounds是一个包含数千个文件的文件夹。在将该文件夹文件添加到tar文件中时,该脚本将花费大量时间(冻结我的GUI),但是我真的不知道它的进度,因为打印不会单独显示每个文件。那是问题。

我尝试过的事情:

我试图在代码的第1部分中获得每个文件的完整路径,但是这会将文件添加到tarfile中,而不在tarfile中创建文件夹或在其各自的文件夹中添加文件。一团糟,因为所有文件都放在同一位置。

所需的解决方案:

1:在将每个文件名添加到tarfile时打印它们。
2:将所有文件存储在tarfile中,而不会破坏每个文件所属的文件夹树。

1 个答案:

答案 0 :(得分:0)

回答我自己的问题,直到提供更好的答案:

# Part 1 became a function
def get_all_files_for_backup(self):
    """Returns a Dict"""
    dict_of_diles = {}
    for dirpath, _, filenames in os.walk(PATH_PROGRAM):
        if not "Backups Folder" in dirpath:  # Exclude this folder
            for filename in filenames:
                if dirpath in dict_of_diles:
                    # If folder exists, append this file to it
                    dict_of_diles[dirpath].append(filename)
                else:
                    # Create a new item in the dict for this folder
                    dict_of_diles[dirpath] = [filename]
    return dict_of_diles

files_to_save = self.get_all_files_for_backup()

# Part 3: We create the tree structure in the tarfile before adding files to it
with tarfile.open(backupfile, "w:gz") as tar:
    for folder, files in files_to_save.items():
        # Create the right tree folders inside the tar file
        relative_folder = folder.replace(PATH_PROGRAM, "")
        if relative_folder.startswith("\\"):
            relative_folder = relative_folder[1:]
            tarfolder = tarfile.TarInfo(relative_folder)
            tarfolder.type = tarfile.DIRTYPE
            tar.addfile(tarfolder)
        # Add the files
        for file in files:
            full_path = os.path.join(folder, file)
            print(full_path)
            # Don't add an arcname if relative folder is none
            if relative_folder == "":
                tar.add(full_path, arcname=file)
            else:
                # Args for tar.add are: Copy from absolute path, Copy to that tar folder.
                tar.add(full_path, arcname="{0}\\{1}".format(relative_folder, file))