0

I have a file that contains bytes in plain text. For example:

00
01
02
A0
A1
A2
FD
FE
FF

I can read the file using:

fh = open(file, 'rb')
my_bytearray = bytearray(fh.read())

However, when I print this it returns:

print(my_bytearray)
b'00\r\n02\r\nA0\r\nA1\r\nA1\r\nA2\r\nFD\r\nFE\r\nFF'

It reads also the \r\n at the end of each line, and also not in hex format, for example not \xFF but FF.

I want to read this file into a bytearray and when I print this bytearray I want to see it as:

print(my_bytearray)
b'\x00\x01\x02\xA0\xA1\xA2\xFD\xFE\xFF'

How can I achieve this?

efe373
  • 151
  • 2
  • 11
  • 1
    What have you been able to achieve so far, at which part are you stuck and what is the problem? Can you read all lines of a file into a list? Can you convert hexadecimal strings into numbers? Can you convert a list of numbers to a bytearray? – mkrieger1 Sep 27 '22 at 08:33
  • 1
    Have you seen https://stackoverflow.com/questions/5649407/hexadecimal-string-to-byte-array-in-python? – mkrieger1 Sep 27 '22 at 08:48
  • @mkrieger1 how can I combine the proposed solution with my problem? I also need to strip carriage return and new line, and then convert it to bytearray. – efe373 Sep 27 '22 at 08:52
  • 1
    Have you tried to use `bytearray.from_hex(fh.read())`? – mkrieger1 Sep 27 '22 at 09:08
  • In general, you can strip carriage return and new line using the `.strip()` string method. But I don't think you need it here. – mkrieger1 Sep 27 '22 at 09:09
  • @mkrieger1 I have tried `fromhex`, not `from_hex`. But it gave me an error, `TypeError: fromhex() argument must be str, not bytes`. EDIT: it works if I open the file with `r` only, not `rb`. – efe373 Sep 27 '22 at 11:59

0 Answers0