【问题标题】:copy files in python with progress bar使用进度条在python中复制文件
【发布时间】:2023-09-02 22:24:01
【问题描述】:

我有一个 python 脚本,可以复制选定位置中存在的文件夹和文件。 此任务完美运行,现在我想在复制时显示进度条。

我使用 tqdm 包在控制台中显示进度条,效果很好,但问题是它在每个文件上显示进度条并每次遍历所有现有文件.

示例:如果一个文件夹包含 128 个文件,它将像这样显示进度条 128 次

100%---------128/128 100%---------128/128

我想要的是为所有正在复制的文件显示进度条 1 次。

代码:

i=0
j=0
z=0
for dirpath, dirnames, files in os.walk(src):           
    print(f'Found directory: {dirpath}')
    if len(dirnames)==0 and len(files)==0:
        print("this directory is empty")
        pass

    for  file in files:
        full_file_name = os.path.join(dirpath, file)

        if os.path.join(dirpath) == src:
            if file.endswith("pdf"):
                if not os.path.exists(dst2):
                    os.mkdir(dst2)
                else:
                    print("the path alredy exist")

                 shutil.copy(full_file_name, dst2)
                i+=1

            elif file.endswith("docx") or file.endswith("doc"):

                 shutil.copy(full_file_name, dst)
                j+=1

        elif os.path.join(dirpath)== src2:
            if file.endswith("pdf"):
                numfile = len(files)

# i think the for loop must not be in this part.
                for z in enumerate(tqdm(numfile)): 
                    sleep(.1)

                 shutil.copy(full_file_name, dst3)
                z+=1

【问题讨论】:

    标签: python for-loop shutil


    【解决方案1】:

    只需创建一个 tkinter 进度条小部件并将值从 for 循环传递给它。 进度完成后关闭窗口,而不是打印到控制台

    Progressbar Image

    使用 tkinter 更新进度条的代码示例:

    from tkinter import *
    from tkinter.ttk import Progressbar
    import time
    def progressbar(ProgressValue):  # Update Progress bar with a int/float/string Round 0-100 #
        ProgBar['value'] = ProgressValue; root.update()
    root = Tk()
    ProgBar = Progressbar(root, length=365, style='black.Horizontal.TProgressbar')
    ProgBar.pack()
    
    time.sleep(2)
    progressbar('10') #Use this
    time.sleep(2)
    progressbar('50')
    time.sleep(2)
    progressbar('100')
    root.mainloop()
    

    【讨论】:

    • 以及如何将进度条的更新与正在复制的文件联系起来?
    • root.overrideredirect(True) 使用此行隐藏标题栏上的最小化最大化和关闭按钮
    • 只除for循环计数(进度条(文件数/100))
    • 统计所有3种文件的总数,除以100,每次都添加到进度条中