Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read Ctrl command characters from a file in Python

Right now I am trying to read and parse a file using Python 2. The creator of the file typed a bunch of lines in the terminal, with (Ctrl A)s within each line, and copied those lines into a text file. So the lines in the file look like "(something)^A(something)". When I use the readlines() function in python to read the file, those "^A" strings cannot be recognized.

I tried to use io.open and codecs.open and set the encoding as UTF-8, but "^A" is clearly not an UTF-8 string. Does anyone know how to read these special control command strings from a file using python? Thank you very much!

like image 975
Andy Chang Avatar asked Jan 20 '26 23:01

Andy Chang


1 Answers

Simply read the file in binary mode like so: open('file.txt', 'rb'). Ctrl-A will be the value 1.

with open('test.txt', 'rb') as f:
    text = f.read()
    for char in text:
        if char == b'\x01': # \x01 stands for the byte with hex value 01
            # Do something
            pass
        else:
            # Do something else
            pass
like image 58
xrisk Avatar answered Jan 23 '26 11:01

xrisk