<p>作为<a href="https://github.com/tqdm/tqdm#how-to-make-a-good-progress-bar" rel="nofollow">explained in the documentation</a>,这是因为您需要提供进度指示器。根据对文件所做的操作,可以使用文件计数或文件大小。</p>
<p>其他答案建议将<code>os.walk()</code>生成器转换为列表,以便获得<code>__len__</code>属性。但是,这将消耗大量内存,具体取决于您拥有的文件总数。</p>
<p>另一种可能是预计算:首先遍历整个文件树并计算文件总数(但不保留文件列表,只保留计数!),然后您可以再次漫游,并为<code>tqdm</code>提供预计算的文件计数:</p>
<pre><code>def walkdir(folder):
"""Walk through every files in a directory"""
for dirpath, dirs, files in os.walk(folder):
for filename in files:
yield os.path.abspath(os.path.join(dirpath, filename))
# Precomputing files count
filescount = 0
for _ in tqdm(walkdir(target_dir)):
filescount += 1
# Computing for real
for filepath in tqdm(walkdir(target_dir), total=filescount):
sleep(0.01)
# etc...
</code></pre>
<p>注意,我在<code>os.walkdir</code>上定义了一个包装函数:因为您是在处理文件而不是目录,所以最好定义一个在文件而不是目录上进行的函数。</p>
<p>但是,您可以在不使用<code>walkdir</code>包装器的情况下获得相同的结果,但这会有点复杂,因为您必须在遍历每个子文件夹之后恢复上一个进度条状态:</p>
<pre><code># Precomputing
filescount = 0
for dirPath, subdirList, fileList in tqdm(os.walk(target_dir)):
filescount += len(filesList)
# Computing for real
last_state = 0
for dirPath, subdirList, fileList in os.walk(target_dir):
sleep(0.01)
dirName = dirPath.split(os.path.sep)[-1]
for fname in tqdm(fileList, total=filescount, initial=last_state):
# do whatever you want here...
# Update last state to resume the progress bar
last_state += len(fileList)
</code></pre>