Removing Ansii chars while writing to file

I have converted some bytes of data & written them to a text file. In the text file I can see few ANSI chars [[2K[90m] been written which does not display if I do print how can I avoid these chars to be displayed in the textfile

sample output from textfile

[2K[90m[00024237ms][DBG ]: ::send_request, request_id:  (19), token_id: 5[0m


[2K[90m[00024250ms][DBG ][CELL]: , request_id:  (19), token_id: 5 error: 0[0m

for decoding the bytes I have done

newdata = Bytesdata.decode("utf-8")

& for writing to text

with open("test.txt", "a+") as file:
    file.write(newdata)

Answer

You can make use of regular expressions to eliminate ansi characters:

import re
def escape_ansi(line):
    ansi_escape =re.compile(r'(x9B|x1B[)[0-?]*[ -/]*[@-~]')
    return ansi_escape.sub('', line)
print(escape_ansi(line = 'tu001b[0;35mSomeTextu001b[0mu001b[0;36m172.18.0.2u001b[0m'))

Source