1
votes

I need to read a binary file in python for which I have a Matlab code already. I'm converting line by line of matlab code to python but stuck at this place, where I'm reading text data from binary file but the output is not in readable text format. Looking for below Matlab's equivalaent code in python

tried struct module in python to unpack but the output string is not readable straight away into a list

Matlab code:

var = char(fread(fid,100,'char'))';

Python code that I tried:

tmp = f.read(100)
abc, = struct.unpack('100c',tmp)

But value of 'abc' is not regular text string, instead it is something like b'/val1 val2 val3 val4'

I need to get the val1, val2, val3, val4 as strings in to a list

1
What are the contents of your text file? - Paolo
This is how exactly I got the data with f.read command b'UsrVal\x00VdetHC\x00VcupHC\x00VdirHC\x00HdirHC\x00UpFlwHC\x00UxHC\x00UyHC\x00UzHC\x00VresHC\x00UxRP\x00UyRP\x00UzRP\x00VresRP\x00Gravity_Axis' - rajgary
I need the strings UsrVal VdetHC VcupHC VdirHC UpFlwHC ...... Gravity_Axis into python list - rajgary
Actually, I have no idea working with binary files, I had corresponding matlab code to read data, so could able to extract data using python code to some extent but I'm unable to read this particular data as string list in python. Help is very much appreciated - rajgary

1 Answers

0
votes

I think using the numpy function fromfile does exactly what you want.

import numpy as np
data = np.fromfile(filename, dtype=np.uint8, count=100,sep='')

count tells how many bytes to read and the empty sep treats the file as binary. See the documentation for details.