If you use the command line a lot (as you should on a Linux or Unix machine, such as the Mac) then you have surely noticed that the text is sometimes printed in color.

How can this be done in Python and how can one create a file that will display part of its content using colors even if you just "cat"-it?

All you have to know for this is that there is something called ANSI escape code that allows you to give instructions to the screen of a command-line window. Some of these instructions are related to color.

Here is an example script:

examples/python/color.py

black   = "\033[0;30m"
red     = "\033[0;31m"
green   = "\033[0;32m"
yellow  = "\033[0;33m"
white   = "\033[0;37m"
nocolor = "\033[0m"

print("Plain text in the default color")
print(green)
print("Green text")
print(red)
print("Red text")
print(f"{yellow} yellow {green} green {red} red")
print(white)
print("White text")
print(black)
print("Black text")

Here I picked some of the colors from ANSI escape code table and put them in variables. Then I only need to print the code to the screeen.

Running this script:

python color.py

resulted in the following output on my computer:

ansi colored output text

Color file content without programming language

If I run the same script, but redirect the output to a file

python color.py > color.txt

I'll get a "regular" text file that looks like this:

examples/python/color.txt

Plain text in the default color

Green text

Red text
 yellow  green  red

White text

Black text

cat color.txt

ansi colored output text