如何在for循环目录中使用tqdm获取进度栏

红麻雀

我试图有条件地从目录加载一些文件。我想要一个来自tqdm的进度条。我目前正在运行:

loaddir = r'D:\Folder'
# loop the files in the directory
print('Data load initiated')
for subdir, dirs, files in os.walk(loaddir_res):
    for name in tqdm(files):
        if name.startswith('Test'):
            #do things

这使

Data load initiated

  0%|          | 0/6723 [00:00<?, ?it/s]
  0%|          | 26/6723 [00:00<00:28, 238.51it/s]
  1%|          | 47/6723 [00:00<00:31, 213.62it/s]
  1%|          | 72/6723 [00:00<00:30, 220.84it/s]
  1%|▏         | 91/6723 [00:00<00:31, 213.59it/s]
  2%|▏         | 115/6723 [00:00<00:30, 213.73it/s]

这有两个问题:

  1. 更新进度后,在Spyder的IPython控制台中会出现新的一行
  2. 我实际上是按文件而不是按'Test'开头的文件计时循环,因此进度和剩余时间不准确。

但是,如果我尝试这样做:

loaddir = r'D:\Folder'
# loop the files in the directory
print('Data load initiated')
for subdir, dirs, files in os.walk(loaddir_res):
    for name in files:
        if tqdm(name.startswith('Test')):
            #do things

我收到以下错误。

Traceback (most recent call last):

  File "<ipython-input-80-b801165d4cdb>", line 21, in <module>
    if tqdm(name.startswith('Probe')):

TypeError: 'NoneType' object cannot be interpreted as an integer

我只想在一行中有一个进度条,每当startswith激活循环时它就会更新

----更新----

我在这里还发现它也可以像这样使用:

files = [f for f in tqdm(files) if f.startswith('Test')]

通过使用tqdm包装迭代器,可以跟踪列表理解的进度。但是,在spyder中,这会为每个进度更新单独显示一行。

---- UPDATE2 ----它实际上在spyder中可以正常工作。有时,如果循环失败,则可能返回到打印一行进度更新。但是在最近的更新之后,我很少见到这种情况。

卡斯珀

首先是答案:

loaddir = r'D:\surfdrive\COMSOL files\Batch folder\Current batch simulation files'
# loop the files in the directory
print('Data load initiated')
for subdir, dirs, files in os.walk(loaddir_res):
    files = [f for f in files if f.startswith('Test')]
    for name in tqdm(files):
        #do things

这将在任何体面的环境(包括裸终端)中工作。解决方案是不提供tqdm未使用的文件名。您可能会发现https://github.com/tqdm/tqdm/wiki/How-to-make-a-great-Progress-Bar很有见地。

其次,多行输出的问题是众所周知的,并且由于不支持回车符(导致某些环境被破坏(https://github.com/tqdm/tqdm#faq-and-known-issues\r)。

Spyder中此问题的正确链接是https://github.com/tqdm/tqdm/issues/512https://github.com/spyder-ide/spyder/issues/6172

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章