我试图有条件地从目录加载一些文件。我想要一个来自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]
这有两个问题:
但是,如果我尝试这样做:
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/512和https://github.com/spyder-ide/spyder/issues/6172
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句