OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

How do I dynamically update terminal text in a for loop with an iterated value?

  • Thread starter Thread starter Thomas
  • Start date Start date
T

Thomas

Guest
I've tried a few solutions on Google, but none have worked so far. Representation of my current code below:

Code:
import sys

filelist = [file1, file2, file3]
totalfiles = str(len(filelist))
count = 0

for f in filelist:

    processdata(f)
    count+=1
    progress = f"Progress: {count}/{totalfiles}"
    print(progress, end="\r")
    sys.stdout.flush()

print("Complete")

Expected behavior is "Progress: 1/3" would appear in the terminal after the first iteration, changing to "Progress: 2/3" on the second and "Progress: 3/3" on the third. However, nothing appears until all iterations are complete, where "Progress: 3/3" is printed.

If I remove end="\r" from my print statement, it will print each of the expected strings on a separate line, which is what I would expect. Any suggestions on where I went wrong?
<p>I've tried a few solutions on Google, but none have worked so far. Representation of my current code below:</p>
<pre><code>import sys

filelist = [file1, file2, file3]
totalfiles = str(len(filelist))
count = 0

for f in filelist:

processdata(f)
count+=1
progress = f"Progress: {count}/{totalfiles}"
print(progress, end="\r")
sys.stdout.flush()

print("Complete")
</code></pre>
<p>Expected behavior is "Progress: 1/3" would appear in the terminal after the first iteration, changing to "Progress: 2/3" on the second and "Progress: 3/3" on the third. However, nothing appears until all iterations are complete, where "Progress: 3/3" is printed.</p>
<p>If I remove end="\r" from my print statement, it will print each of the expected strings on a separate line, which is what I would expect. Any suggestions on where I went wrong?</p>
 

Latest posts

Top