代码之家  ›  专栏  ›  技术社区  ›  Saelyth

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

  •  1
  • Saelyth  · 技术社区  · 7 年前

    我正在创建一个脚本来备份包含多个文件夹、数据库和数百个文件夹和文件的整个程序。为此,我使用了这段代码,它工作得很好(为此做了一些编辑)。

    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中创建文件夹或在其各自的文件夹中添加文件。因为所有的文件都在同一个地方,所以一切都一团糟。

    理想的解决方案:


    2:将所有文件存储在tarfile中,而不破坏每个文件所属的文件夹树。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Saelyth    7 年前

    在提供更好的答案之前,回答我自己的问题:

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