Reputation: 23
I have a file containing urls (google.com, microsoft.com, etc). I want to print one url, then clear previous line from it. again write another url above. Code sample is below:
import sys
with open('url.txt') as u:
for line in u:
line=line.strip()
print(line, end="\r")
#also tried
sys.stdout.write("\r{0}".format(line))
sys.stdout.flush()
above code doesn't delete all previous chars. Example: "google.com" after "microsoft.com" will print as "google.com.com". Anybody can tell me how to delete previous line completely?
Upvotes: 0
Views: 127
Reputation: 198
Try this:
import sys
import time
with open('url.txt') as u:
lastline = ""
for count, line in enumerate(u.readlines()):
if count != 0: # do not delay on first item outputted
time.sleep(4) # 4 sec delay so user can read before next text appears
line = str(line).strip("\n")
print(' ' * (len(lastline) + 1), end='\r') # clear last line
print(line, end='\r')
lastline = line
Tested on windows 10
Though, the cursor will be blinking at the start. To fix this, you can install the cursor module by pip install cursor
and then use this slightly modified code:
import sys
import time
import cursor
with open('url.txt') as u:
lastline = ""
for count, line in enumerate(u.readlines()):
if count != 0: # do not delay on first item outputted
time.sleep(4) # 4 sec delay so user can read before next text appears
line = str(line).strip("\n")
print(' ' * (len(lastline) + 1), end='\r') # clear last line
print(line, end='\r')
lastline = line
cursor.hide()
cursor.show()
Upvotes: 1