0

New to this python thing. A little while ago I saved off output from an external device that was connected to a serial port as I would not be able to keep that device. I read in the data at the serial port as bytes with the intention of creating an emulator for that device. The data was saved one 'byte' per line to a file as example extract below.

b'\x9a'
b'X'
b'}'
b'}'
b'x'
b'\x8c'

I would like to read in each line from the data capture and append what would have been the original byte to a byte array. I have tried various append() and concatenation operations (+=) on a bytearray but the above lines are python string objects and these operations fail.

Is there an easy way (a built-in way?) to add each of the original byte values of these lines to a byte array?

Thanks.

M

Update I came across the .encode() string method and have created a crude function to meet my needs.

def string2byte(str):
    # the 'byte' string will consist of 5, 6 or 8 characters including the newline
    # as in b',' or b'\r' or b'\x0A'
    if len(str) == 5:
        return str[2].encode('Latin-1')
    elif len(str) == 6:
        return str[3].encode('Latin-1')
    else:
        return str[4:6].encode('Latin-1')

...well, it is functional.

If anyone knows of a more elegant solution perhaps you would be kind enough to post this.

2
  • your code seems incorrect e.g., for "b'\\r'\n" your code produces b'r' instead of b'\r'. Commented Mar 18, 2014 at 18:16
  • Thank you, JF. Missed that. Commented Mar 18, 2014 at 21:11

1 Answer 1

1

b'\x9a' is a literal representation of the byte 0x9a in Python source code. If your file literally contains these seven characters b'\x9a' then it is bad because you could have saved it using only one byte. You could convert it to a byte using ast.literal_eval():

import ast

with open('input') as file:
    a = b"".join(map(ast.literal_eval, file)) # assume 1 byte literal per line
3
  • @J.F. I created the file by reading all the bytes at the port into a bytes array. I did some test/checks at this stage to discover and/or confirm the nature of the data. i then wrote out the data in the byte array one byte at a time to a file (which I am now trying to process). The code you provided seems to work just fine, JF. Thank you. Guess I've a lot of reading to do now to work it all out. Commented Mar 18, 2014 at 21:20
  • @eryksun J.F.'s code seems to work fine in python3 as you suggested. Thank you too. take care all. Commented Mar 18, 2014 at 21:21
  • @eryksun: Indeed, ast.literal_eval("b'\\x9a'\n") works on Python 3. I've removed the incorrect remark. Commented Mar 19, 2014 at 4:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.