Sid
Sid

Reputation: 23

Animation on terminal using python

The code for terminal animation I'm using I'm trying to make an animation on terminal, and have been successful in making an animation using the code in the snapshot I've attached. The problem is that this code prints the entire contents of the first file and clears the entire terminal and prints content of second file. Making a frame by frame style animation. What I want to accomplish is to first print contents of first file and without clearing overwriting the contents of the second file on top of printed first file content.

import os, time, sys

os.system('cls')
filenames = ["0.txt", "1.txt"]

with open("0.txt") as f0:
  zero = f0.read()

with open("1.txt") as f1:
  one = f1.read()

for i in range(10):
  for c in zero:
    sys.stdout.write(c)
    time.sleep(.0001)

  os.system('cls')

  for c in one:
    sys.stdout.write(c)
    time.sleep(.0001)

  os.system('cls')

Imagine the :

print("content on one line",end="\r") style return carraige overwrite printing on one line but for entire paragraphs.

Is there any way to go back to the begining of the first files print and overwriting it with second file?

Upvotes: 2

Views: 1168

Answers (1)

jsbueno
jsbueno

Reputation: 110466

You are erasing the terminal by calling cls - that will obviously clear the terminal. You need to use ANSI sequence commands, or a library that will use then or an equivalent of them for you, in order to position the cursor at the screen home without clearing it.

Since you are on Windows, the colorama module should enable you to do that - at the very least it enables the ANSI sequences you need.

For more advanced animation, like color effects, use unicode espcial characters like encircled letters, drawing with block-characters, one might want to use terminedia (disclaimer: I am the author) - however it is not windows ready yet - and it will use colorama to enable its functions under Windows anyway.

Upvotes: 1

Related Questions