Search code examples
pythonread-writefile-read

How to decode a DAT file in python?


I'm trying to read bytes from a DAT file. I know the data is supposed to be in either Binary or Hex. But when I try to read the bytes it prints out weird symbols. I'm assuming they are ascii values. I tried converting them but I keep getting the error message that 'str' cannot be converted. Does anyone know how I can decode it? And is read() the correct function to use for this?

import time
import binascii
import csv
import serial

with open('Example CARESCAPE Datalog.dat') as binary_file:
    for num in range(1,10):
        data = binary_file.readline()
        print(data)

Here is the link to a screenshot of the weird symbols I get


Solution

  • If your .dat file is not text, you should open it as a binary file with 'rb' (per Python docs):

    with open('Example CARESCAPE Datalog.dat', 'rb') as binary_file:
    

    You'll have to decode the bytes yourself:

    Note: Files opened in binary mode (including 'rb' in the mode argument) return contents as bytes objects without any decoding.