Print() to Previous Line

Print() to previous line?

In Python 3, you can suppress the automatic newline by supplying end="" to print():

print("Random string value", end="")
if a==0:
print(" is random")

See How to print without newline or space?

Append to previous line

You need to flush the buffer after each print statement (that uses end="") in order to ensure that the messages are pushed to the console immediately. See print() documentation.

Working Example with flush parameter of print function:

import time

print("Creating folders... ", end="", flush=True)
time.sleep(2) # fake process
print("Creating folders... ", end="", flush=True)

Working Example with manual flushing:

import time
import sys

print("Creating folders... ", end="")
time.sleep(2) # fake process
print("Creating files... ", end="")

See it in action!

Java - How to print() output to previous line after input

You should look into Ansi Escape Codes.

Something like:

public void update() {
final String guessString =;

System.out.println("\033[1A\033[" + guessString.length() + 'C'
+ "\t{next col}");

will result in:

1234   {next col}

(where 1234, followed by {RETURN} was entered by the user; in an appropriately supporting console.

"\033[1A" moves the cursor up 1 row; and "\033[xC" moves the cursor x to the right (where above we calculate x as the length of their guess).

Another option that you have with this approach is to clear the console ("\033[2J") so that you can just completely re-draw the table (which is probably easier to maintain).

How to start output a new line and then go back up to the previous line java

You're not going to be able to accomplish this using System.out.print.

Instead, you'll need some other variable to hold your text while you're working on it.

I'd recommend using a string array (or ArrayList if you don't know how many lines there will be in advance), with each entry corresponding to a line of text.

ArrayList<String> lines = new ArrayList<String>();
lines.add("|. |");
lines.add("| .|");

This way, you can easily go back to edit a previous line as follows:

lines.set(0, lines.get(0).concat("text to add"); // Edit a previous line

Then, when you're ready to display the results:

for(String s : lines)

Print a number of previous lines after matching string found in line in python

This is a perfect use case for a length limited collections.deque:

from collections import deque

line_history = deque(maxlen=25)
with open(file) as input:
for line in input:
if "error code" in line:
print(*line_history, line, sep='')
# Clear history so if two errors seen in close proximity, we don't
# echo some lines twice
# When deque reaches 25 lines, will automatically evict oldest

Complete explanation of why I chose this approach (skip if you don't really care):

This isn't solvable in a good/safe way using for/range, because indexing only makes sense if you load the whole file into memory; the file on disk has no idea where lines begin and end, so you can't just ask for "line #357 of the file" without reading it from the beginning to find lines 1 through 356. You'd either end up repeatedly rereading the file, or slurping the whole file into an in-memory sequence (e.g. list/tuple) to have indexing make sense.

For a log file, you have to assume it could be quite large (I regularly deal with multi-gigabyte log files), to the point where loading it into memory would exhaust main memory, so slurping is a bad idea, and rereading the file from scratch each time you hit an error is almost as bad (it's slow, but it's reliably slow I guess?). The deque based approach means your peak memory usage is based on the 27 longest lines in the file, rather than the total file size.

A naïve solution with nothing but built-ins could be as simple as:

with open(file) as input:
lines = tuple(input) # Slurps all lines from file
for i, line in enumerate(lines):
if "error code" in line:
print(*lines[max(i-25, 0):i], line, sep='')

but like I said, this requires enough memory to hold your entire log file in memory at once, which is a bad thing to count on. It also repeats lines when two errors occur in close proximity, because unlike deque, you don't get an easy way to empty your recent memory; you'd have to manually track the index of the last print to restrict your slice.

Note that even then, I didn't use range; range is a crutch a lot of people coming from C backgrounds rely on, but it's usually the wrong way to solve a problem in Python. In cases where an index is needed (it usually isn't), you usually need the value too, so enumerate based solutions are superior; most of the time, you don't need an index at all, so direct iteration (or paired iteration with zip or the like) is the correct solution.

print a previous line based on a condition in python

Use tee to run a pair of iterators across inf. This only stores five lines in memory at any given time:

from itertools import tee

with open("SFU.txt") as inf:
# set up iterators
cfg,res = tee(inf)
# advance cfg by four lines
for i in range(4):

for c,r in zip(cfg, res):
if "configuration" in c:

and, as expected, results in

This is planet Mars

Edit: if you want to edit the -4th line, I suggest

def edited(r):
# make your changes to r
return new_r

with open("SFU.txt") as inf, open("edited.txt", "w") as outf:
# set up iterators
cfg, res = tee(inf)
for i in range(4):

# iterate through in tandem
for c, r in zip(cfg, res):
if "configuration" in c:
r = edited(r)

# reached end - write out remaining queued values
for r in res:

Update previous line instead print new line

You cannot move up in the terminal like that, unless using some complex lib as curses.
You can use the "clear screen" trick, maybe that would achieve what you want.

#include <stdio.h>
#include <stdlib.h>

int main()
int a,b;
system("clear"); // or "cls" on windows
printf("Enter two integer to add\r");
system("clear"); // or "cls" on windows
printf("Your value is -- %d",a);

return 0;

Java carriage to previous line

I don't think you can.

You would normally use System.out.print for the first part instead and use a println() or a '\n' once you're sure your line ended.

Related Topics

Leave a reply