This question already has answers here:
How to overwrite the previous print to stdout?
(18 answers)
Closed 1 year ago.
I want to make a game in the python console, so I need to write out lines, and then re-write them. I started building up code for it, and came up with this:
import sys
while 1:
#I will calculate what to write here, and store it in display
display = ["thing", "other thing", "2nd other thing"]
#Move the writing start back to the beginning
for x in display: sys.stdout.write("\r")
#Write the contents of display
for x in display: sys.stdout.write(x + "\n")
However, the code does not erase the previously written text. It just repetitively prints the display list. How can I make it erase the text?
Edit:
Similar Answer How to overwrite the previous print to stdout in python?
Method:
You can do this by printing out as many whitespaces as you have characters on that line
However this would only be possible in a clean manner if you know the length of everything being printed.
For example if you know the length you can do the following
print("\r")
print(" " * length_of_line)
print("\r")
Otherwise if printing long line isn't a concern, you can adopt the brute-force method of print a load of whitespaces and hope it overwrites the whole line
print("\r")
print(" " * a_large_number)
print("\r")
You cannot use the "\r" separately from the print statement and I think you can only use it in this way with the print statement.
An implementation with the print statement would look like this:
for i in range(3): #No endless loop
display = ["thing", "other thing", "2nd other thing"]
for x in display: print(x, end="\r")
This would result in every line overwriting the previous one.
Also have a look here, there they also discuss different methods.
Related
This question already has answers here:
Delete last printed character python
(3 answers)
Closed 4 years ago.
I'm trying to delete the last character I've printed from the previous line in python, e.g if I do print ("hello world")
I will get hello world outputted, but I'm wondering after it's been outputted would there be a way to remove the d at the end of the output so it would now only say hello worl... in short is there a way to remove the end character of an already printed line?
Thanks
There is no way to perform operations on data that has been output since it is not stored in memory as a variable. You can however overwrite the location on the screen (if you are dealing with something like a terminal) that it is printed on to 'remove' the old data.
Here is a function you can add and call in your code to send text to a specific location on the terminal display:
import sys
def PrintLocate(row, column, text):
sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (row, column, text))
sys.stdout.flush()
# Elsewhere
PrintLocate(13, 37, "Hello World")
PrintLocate(13, 37 + len("Hello Worl"), " ")
This question already has answers here:
How to overwrite the previous print to stdout?
(18 answers)
Closed 7 years ago.
I want to do something like this.
calculating 50%
calculating 60%
calculating 70%
but in a single line.
Did hours of googling and couldn't find anything. :)
You can do something like this:
print '50%%',
print '\r60%%',
print '\r70%%',
The comma makes sure there is no newline. The \r clears the current line, so that the previous 50% is removed, and overwritten with the 60%. However, because the print is not flushed (like without the comma), it can happen that you will not see some lines printed. For that, you'll need to flush the output, by using this:
import sys
sys.stdout.flush()
It depends whether you want to overwrite the previous thing or to really write all three statements on one line.
The latter you can do by
import sys
sys.stdout.write("calculating 50%")
sys.stdout.write("calculating 60%")
sys.stdout.write("calculating 70%")
The former would be probably achieved by terminal escape sequences an would be different for different OSs.
As an attorney I am a total newbie in programimg. As an enthusiastic newbie, I learn a lot. (what are variables, ect.) ).
So I'm working a lot with dir() and I'm looking into results. It would by nicer if I could see the output in one or more columns. So I want to write my first program which write for example dir(sys) in a output file in columns.
So far I've got this:
textfile = open('output.txt','w')
syslist = dir(sys)
for x in syslist:
print(x)
The output on display is exactly what I want, but when I use the .write like:
textfile = open('output.txt','w')
syslist = dir(sys)
for x in syslist:
textfile.write(x)
textfile.close()
The text is in lines.
Can anyone pleaase help me, how to write the output of dir(sys) to a file in columns?
If I can ask you, please write the easysiet way, because I really have to look almost after for every word you write in documentation. Thanks in advance.
print adds a newline after the string printed by default, file.write doesn't. You can do:
for x in syslist: textfile.write("%s\n" % x)
...to add newlines as you're appending. Or:
for x in syslist: textfile.write("%s\t" % x)
...for tabs in between.
I hope this is clear for you "prima facie" ;)
The other answers seem to be correct if they guess that you're trying to add newlines that .write doesn't provide. But since you're new to programming, I'll point out some good practices in python that end up making your life easier:
with open('output.txt', 'w') as textfile:
for x in dir(sys):
textfile.write('{f}\n'.format(f=x))
The 'with' uses 'open' as a context manager. It automatically closes the file it opens, and allows you to see at a quick glance where the file is open. Only keep things inside the context manager that need to be there. Also, using .format is often encouraged.
Welcome to Python!
The following code will give you a tab-separated list in three columns, but it won't justify the output for you. It's not fully optimized so it should be easier to understand, and I've commented the portions that were added.
textfile = open('output.txt','w')
syslist = dir(sys)
MAX_COLUMNS = 3 # Maximum number of columns to print
colcount = 0 # Track the column number
for x in syslist:
# First thing we do is add one to the column count when
# starting the loop. Since we're doing some math on it below
# we want to make sure we don't divide by zero.
colcount += 1
textfile.write(x)
# After each entry, add a tab character ("\t")
textfile.write("\t")
# Now, check the column count against the MAX_COLUMNS. We
# use a modulus operator (%) to get the remainder after dividing;
# any number divisible by 3 in our example will return '0'
# via modulus.
if colcount % MAX_COLUMNS == 0:
# Now write out a new-line ("\n") to move to the next line.
textfile.write("\n")
textfile.close()
Hope that helps!
I'm a little confused by your question, but I imagine the answer is as simple as adding in tabs. So change textfile.write(x) to textfile.write(x + "\t"), no? You can adjust the number of tabs based on the size of the data.
I'm editing my answer.
Note that dir(sys) gives you an array of string values. These string values do not have any formatting. The print x command adds a newline character by default, which is why you are seeing them each on their own line. However, write does not. So when you call write, you need to add in any necessary formatting. If you want it to look identical to the output of print, you need to add in write(x + "\n") to get those newline characters that print was automatically including.
This question already has answers here:
How to print one character at a time on one line?
(4 answers)
Closed 8 years ago.
Ok this is going to be hard to ask/explain but bear with me.
Im trying to just make things look cool when I use the while True command.
What I am trying to do Is make it type stuff slower or one letter at a time.
For example, here is my code.
while True:
print ("010101010101010101010101010101")
print ("010101010101001010101010101010")
print ("010101010101010101010101010101")
When I do that it obviously rapidly repeats the commands I entered in the file.
I am aware there is the following,
import time
time.sleep(5)
But I wan't it to type it one at a time, not on a 5 second relay.
I hope you can understand what I am trying to ask. Thank you so much for helping me.
Here's one possibility:
import sys
import time
def cool_print(str):
for char in str:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(0.05) # Or whatever delay you'd like
print # One last print to make sure that you move to a new line
Then instead of print ("010101010101010101010101010101"), you'd use cool_print("010101010101010101010101010101").
It sounds like you want a delay between each actual character, so you need to call sleep in between each one:
import time
while True:
for binary_char in "10101010101010101":
time.sleep(5) # Replace this with a much smaller number, probably
print binary_char, # Remove trailing comma to print each character on new line
This question already has an answer here:
Why doesn't print output show up immediately in the terminal when there is no newline at the end?
(1 answer)
Closed last month.
I'm trying to create a progress bar in the terminal, by repeatedly printing # symbols on the same line.
When i tell Python to not add newlines - using print('#', end='') in Python 3 or print '#', in Python 2 - it prints as desired, but not until the whole function is finished. For example:
import time
i = 0
def status():
print('#', end='')
while i < 60:
status()
time.sleep(1)
i += 1
This should print '#' every second but it doesn't. It prints them all after 60 seconds. Using just print('#') prints it out every second as expected. How can I fix this?
You probably need to flush the output buffer after each print invocation. See How to flush output of Python print?
Python is buffering the output until a newline (or until a certain size), meaning it won't print anything until the buffer gets a newline character \n. This is because printing is really costly in terms of performance, so it's better to fill a small buffer and only print once in a while instead.
If you want it to print immediately, you need to flush it manually. This can be done by setting the flush keyword argument to True.
import time
word = "One letter at a time"
for letter in word:
print(letter, end='', flush=True)
time.sleep(0.25)
You can always use the strip() function.