gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:26:58 24 4
gpt4 key购买 nike

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

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 是一个包含数千个文件的文件夹。该脚本将花费大量时间(卡住我的 GUI),同时将该文件夹文件添加到 tar 文件,但我并不真正知道它的进度,因为打印没有单独向我显示每个文件。这就是问题所在。

我尝试过的:

我尝试在代码的第 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))

关于python - 备份文件夹树,但单独打印每个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53785420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com