Python print one line above

Is there a way in python to print something in the command line above the last line printed? Or, similarly to what I want to achieve, remain the last line intact, that is, not overwrite it.

The goal of this is to let the last line in the command line a status/precentage bar.

Output example:

File 1 processed
(0.1% Completed)

Next refresh:

File 1 processed
File 2 processed
(0.2% Completed)

Next refresh:

File 1 processed
File 2 processed
File 3 processed
(0.3% Completed)

Python print one line above

martineau

115k25 gold badges160 silver badges284 bronze badges

asked Apr 12, 2017 at 15:23

from time import sleep
erase = '\x1b[1A\x1b[2K'

def download(number):
    print(erase + "File {} processed".format(number))

def completed(percent):
    print("({:1.1}% Completed)".format(percent))

for i in range(1,4):
    download(i)
    completed(i/10)
    sleep(1)

Works in my python 3.4, final output is:

File 1 processed
File 2 processed
File 3 processed
(0.3% Completed)

If you want read more about terminal escape codes see: Wikipedia's ANSI escape codes article.

As requested, example with a space:

from time import sleep
erase = '\x1b[1A\x1b[2K'

def download(number):
    print(erase*2 + "File {} processed".format(number))

def completed(percent):
    print("\n({:1.1}% Completed)".format(percent))

print("\n(0.0% Completed)")
for i in range(1,5):
    download(i)
    completed(i/10)
    sleep(1)

The final output is:

File 1 processed
File 2 processed
File 3 processed
File 4 processed

(0.4% Completed)

Python print one line above

martineau

115k25 gold badges160 silver badges284 bronze badges

answered Apr 12, 2017 at 15:43

Python print one line above

muckamucka

1,2463 gold badges23 silver badges35 bronze badges

2

Take a look at the \r command. This could do the trick.

for i in range(2):
    print '\rFile %s processed' % i
    print '(0.%s%% Completed)' % i,

Output is:

File 0 processed
File 1 processed
(0.1% Completed)

answered Apr 12, 2017 at 15:40

NuageuxNuageux

1,6581 gold badge16 silver badges28 bronze badges

2

The print function is an important function in Python, as it is used to redirect output to the terminal. The output can also be redirected to a file.

The print function, by default, prints on a new line every time. This is due to the definition of print() in the Python documentation.

Why does Python's print function print on a new line by default?

In the snippet below, we can see that by default the value of end is \n. This means that every print statement would end with a \n. Note that \n represents a new-line character.

Python print one line above
Source: Python documentation.

Let's see an example of the print function.

Code Example:

# using Print with default settings

print("This will be printed")
print("in separate lines")

Output:

Python print one line above

In the example above, lines would be printed separately due to the definition: end='\n'.

Sometimes, we need to print strings on the same line. This is specially useful when we are reading files in Python. When we read files, we get a blank between lines by default.

Let's see an example. We have a file named rainbow.txt with contents shown below:

Python print one line above
Contents of file rainbow.txt

Code:

fhand = open('rainbow.txt')
for line in fhand:
  print(line)

In the code above, we have used a file handler fhand to access the file. Next, we iterate through the lines using a for loop.

Output:

When we print the contents, the results are like this:

Python print one line above

The extra blank line is due to the presence of \n at the end of each line in the file which moves the cursor to the next line. Finally the blank line gets added due to print function's behavior as discussed in the last section.

Let's say we want to remove these. To do that, we can make some changes. For this, we need to change the default behavior of print. We'll see how to do that in detail in the coming sections.

Option #1 – How to modify the value of end in a print function

Let's customize the value of end in the print function. We'll set it to ' ' which is a space.

Code Example:

# Customizing the value of 'end'

print("This is string 1 same line", end=' ')
print("This is string 2 different line")

Output:

Python print one line above

Now we can see that instead of a new line (\n) we are telling the print function to add a blank character at the end.

We can also provide another character instead of a blank like this:

# Customizing the value of 'end' with a custom separator

print("This is string 1 same line", end=';')
print("This is string 2 different line")

Output:

Python print one line above

Usage: The above example is just a way to print on the same line with the separating character of your choice.

Let's see another example. We can iterate through a list of items and print them on the same line with end = ' ' .

# iterating lists

list_fruits = ['red','blue', 'green', 'orange']  
for i in list_fruits:  
    print(i, end = ' ')  
    

Output:

Python print one line above

Option #2 – Remove whitespace using rstrip() in files

We can remove certain characters around a string using strip(). By default, every line in a file has "\n" at the end. As we are concerned with only the character on the right, we will use rstrip() which stands for right-strip. We'll discuss an example of rstrip() next.

You can learn more about the strip() method in this blog post.

Back to our file printing example

Remember, we discussed a file printing example where extra lines were being printed:

Python print one line above

Let's modify the code a bit using rstrip().

print("1. Removing extra blank line")

fhand = open('rainbow.txt')
for line in fhand:
  line=line.rstrip()
  print(line)

print("\n")

print("2. Printing all in the same line")
fhand = open('rainbow.txt')
for line in fhand:
  line=line.rstrip("\n")
  print(line, end = ' ')

Output

First, we have removed the extra whitespace with rstrip(). In the next step we have removed the trailing line again with rstrip("\n") and end=' ' to get the output in a single line.

Python print one line above

Wrapping up

We have seen how we can print in Python without a new line. We have also seen how we can print lines in a file without extra trailing lines. I hope you found this tutorial helpful.

Share your thoughts with me on Twitter!

You can read my other posts here.

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

How do I print on one line in Python?

To print on the same line in Python, add a second argument, end=' ', to the print() function call. print("It's me.")

How do I print a previous line in Python?

go to the (start of the) previous line: \033[F.

How do you override a new line in Python?

By default, Python's print statement ends each string that is passed into the function with a newline character, \n . This behavior can be overridden with the function's end parameter, which is the core of this method. Rather than ending the output with a newline, we use a carriage return.

How do you print on the same line without space in Python?

The end=”” is used to print on same line without space. Keeping the doube quotes empty merge all the elements together in the same line.