簡體   English   中英

備份一棵文件夾樹,但分別打印每個文件

[英]Backup a tree of folders, but print each file individually

我正在創建一個腳本來備份具有多個文件夾,數據庫以及數百個文件夾和文件的整個程序。 為此,我使用了這段代碼,並且效果很好(為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中,而不會破壞每個文件所屬的文件夾樹。

回答我自己的問題,直到提供更好的答案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM