如何将进度条(例如tqdm)附加到f.write()?

问题描述 投票:0回答:1
with open("./output/" + filename + ".txt", "w") as f:
    f.write(very_long_string)

我有一个很长的字符串,我必须写入文件,我想在写入过程中附加一个进度条。如何将进度条挂接到写入过程?

我查看了一个相关问题(?)并尝试了这个,但它不太有效:

class tqdmIOWrapper(io.TextIOBase):
    def __init__(self, file, callback):
        self.file = file
        self.callback = callback

    def write(self, string):
        buf = self.file.write(string)
        if buf:
            self.callback(buf)
        return buf

with open("./output/" + filename + ".js", "w") as f:
    f.write("var " + filename + " = ")
    with tqdm(
        total=len(very_long_string), desc="Printing: " + filename, mininterval=1
    ) as pbar:
        wrapper = tqdmIOWrapper(f, pbar.update)
        wrapper.write(very_long_string)
        pbar.update()

进度条仅在整个字符串写入后才显示,看起来我根本没有将进度条挂接到写入过程。这是控制台的示例输出(过程花费了超过 1 秒):

Printing: test:   0%|                                                             | 0/466073757 [00:00<?, ?it/s]466073757
Printing: test: 466073758it [00:01, 396677046.13it/s]

有没有办法将进度条挂接到

f.write()
进程?

另一个相关问题没有答案

编辑:回复对一个有效但非常慢的一次一个字符的代码的评论(不是首选):

with open("./output/" + filename + ".txt", "w") as f:
    with tqdm(total=len(very_long_string)) as pbar:
        for char in very_long_string:
            f.write(char)
            pbar.update()
python file-io progress-bar file-writing tqdm
1个回答
0
投票

就像一次 1 个字符,但一次 100 万个:

with open("./output/" + filename + ".txt", "w") as f:
    n = len(very_long_string)
    k = 10 ** 6
    with tqdm(total=n) as pbar:
        for i in range(0, n, k):
            chunk = very_long_string[i : i+k]
            f.write(chunk)
            pbar.update(len(chunk))
© www.soinside.com 2019 - 2024. All rights reserved.