Is there a way to clear your printed text in python?

拥有回忆 提交于 2020-02-23 10:05:05

问题


I have wanted for a long time to find out how to clear something like print("example") in python, but I cant seem to find anyway or figure anything out.

print("Hey")
>Hey

Now I need to clear it, and write some new text.

print("How is your day?")

It would print.

Hey

>How is your day?

But I want to clear the "Hey" so the user shouldnt look at both at same time, and it looks kinda messy.


回答1:


import os
os.system('cls')

Or os.system('clear') on unix (mac and linux). If you don't want the scroll up either, then you can do this:

os.system("printf '\033c'") should get rid of scroll back too. Something that works on all systems:

import os
os.system('cls' if os.name == 'nt' else "printf '\033c'")



回答2:


I think this is what you want to do:

take the cursor one line up and delete the line

this can be done like using the code below

import sys
import time

def delete_last_line():
    "Use this function to delete the last line in the STDOUT"

    #cursor up one line
    sys.stdout.write('\x1b[1A')

    #delete last line
    sys.stdout.write('\x1b[2K')


########## FOR DEMO ################
if __name__ == "__main__":
    print("hello")
    print("this line will be delete after 2 seconds")
    time.sleep(2)
    delete_last_line()
####################################



回答3:


Well; i have a temporary way:-

print('Hey', end = '')

for i in range(4):
    print('\b', end = '')
print('How is your day?')



回答4:


import time
Dots = "."
total = 0
count = 0
while count < 5:
    if total<1:
        print("[+]Saving" + Dots,end="")
    total+=1
    time.sleep(1)
    print(Dots,end="")

This code works perfectly fine...



来源:https://stackoverflow.com/questions/19596750/is-there-a-way-to-clear-your-printed-text-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!