2

I am currently using a Python version 3.8.3.

So, what I am trying to achieve is overwriting (or updating) only a single line of output string in Python.

Let's say the lines would be something like:

=== : Downloading (RandomFile.zip)
=== : 0.0MB/50.0MB - 0%
=== : Please wait...

and I am only willing to update the second line so that the users could see it processing, but keep the first and third lines as they are.

Of course, I have tried "Carriage Return (\r)", but no luck :/...

(Have gone through the escape sequences, but guess I have not fully understood about how carriage return works...)

Python Code:

from time import sleep

file_name = 'RandomFile.zip'

file_size = 50.0
current_file_size = 0.0

while current_file_size <= file_size:
    current_percentage = int(current_file_size / file_size * 100)

    print(f"=== : Downloading ({file_name})")
    print(f"=== : {current_file_size}MB/{file_size}MB - {current_percentage}%", end='\r')
    print("=== : Please wait...")

    current_file_size += 5.0

    sleep(0.05)

Output:

=== : Downloading (RandomFile.zip)
=== : Please wait... 0%
=== : Downloading (RandomFile.zip)
=== : Please wait... 10%
=== : Downloading (RandomFile.zip)
=== : Please wait...- 20%
=== : Downloading (RandomFile.zip)
=== : Please wait...- 30%
=== : Downloading (RandomFile.zip)
=== : Please wait...- 40%
=== : Downloading (RandomFile.zip)
=== : Please wait...- 50%
=== : Downloading (RandomFile.zip)
=== : Please wait...- 60%
=== : Downloading (RandomFile.zip)
=== : Please wait...- 70%
=== : Downloading (RandomFile.zip)
=== : Please wait...- 80%
=== : Downloading (RandomFile.zip)
=== : Please wait...- 90%
=== : Downloading (RandomFile.zip)
=== : Please wait...- 100%

Could I please get a help?

Thank you!

Layback
  • 31
  • 3
  • You are printing the first and third lines each time *with* line breaks, this messes up the formatting. – mkrieger1 Jun 13 '20 at 22:50
  • @Alireza, I'll have a look into it. Thanks!! – Layback Jun 13 '20 at 22:52
  • The third line makes this unnecessarily hard. It requires that you move the cursor *up* one line before printing the second line again. If you can live without the third line, just omit it and move the first line to before the loop. – mkrieger1 Jun 13 '20 at 22:52
  • @mkrieger1, Yes, I just realized why formatting is so messed up like that... I'll have a look into Alireze's reference and see how I go with it! – Layback Jun 13 '20 at 22:53

0 Answers0