0

I have to read UART device through the USB port and store the incoming bytes in a .txt file.

I use the following command:

while 1:
    x=ser.read()
    f.write(str(x))    #f is the file object

However this converts some bytes to their corresponding ascii characters and stores some as it is

Example:

b'\x55' is stored as b'U'.

But, b'\xaa' is stored as the string itself (i.e. b'\xaa').

If I use chr(int.from_bytes()) it gives the following error:

UnicodeEncodeError: 'cp932' codec can't encode character '\xaa' in position 0: illegal multibyte sequence

Is there a method by which I can store all the incoming bytes as the bytes without converting some to ascii characters (eg: b'\x55' stored as string b'\x55' not b'U'), as this causes problems when I process the data further.

I am using python-3.7 on 64 bit windows 10

Community
  • 1
  • 1
  • How does the `.txt` file look like??? – U13-Forward Jun 12 '18 at 04:44
  • If your data is not text, you can either store it as is in a binary file, or you will have to encode it to some textual representation. Using `str` as you do does the latter, maybe you want to do the former? – Thierry Lathuille Jun 12 '18 at 04:53
  • I'd say you should store the data in binary format as you receive it and then use a hex viewer / editor to open it. – Klaus D. Jun 12 '18 at 04:55

1 Answers1

0

try the following link: https://www.devdungeon.com/content/working-binary-data-python and also Python writing binary

with open("outfile.txt", "br+") as outfile:
   outfile.write(ser.read())
PydPiper
  • 411
  • 5
  • 18