Need help reading in a binary file - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: Need help reading in a binary file (/thread-3765.html) |
Need help reading in a binary file - shaynehansen - Jun-21-2017 I need help figuring out how to read in a binary file, and then placing it into a numpy array. The error I am getting is: AttributeError: 'ReadBinary' object has no attribute 'array' Thank you in advance. import numpy as np import collections class ReadBinary(collections.Mapping): ''' Reads in Binary Code. ''' filename = 'R033P010BDAS.eud' def __init__(self): self.cache= [] with open(self.filename, 'rb') as self.file: self.filecontent = self.file.read() def __len__(self): return len(self.filecontent) def __iter__(self): self.cache_index = 0 return self def __next__(self): self.cache_index += 1 if len(self.filecontent) >= self.cache_index: return self.cache[self.cache_index-1] if self.file.closed: raise StopIteration row= self.filecontent.read() if not row: self.file.close() raise StopIteration array = np.fromstring(self.filecontent) self.cache.append(array) return array def __getitem__(): pass read = ReadBinary() print(read.array) RE: Need help reading in a binary file - Larz60+ - Jun-21-2017 Please show the entire traceback. It contains valuable information and I believe part of the prblem is that you need to append .decode('utf-8') to your read statement, like: self.filecontent = self.file.read().decode('utf-8') RE: Need help reading in a binary file - zivoni - Jun-22-2017 There is no array attribute defined in your class, so its correct that read.array raises AttributeError. As you have implemented __next__ and __iter__ , it seems that proper way to use your class would beread = iter(ReadBinary()) # to get iterator next(read) # should return first array value ...Without calling iter first next(read) would raise error (no self.cache_index defined in __init__). Unfortunately there are other problems too, for example self.filecontent is a binary string (without .read() method), so self.filecontent.read() would raise error. Morever self.filecontent contains entire file, therefore entire logic in __next__ seems rather questionable (and erroneous). I am not sure what do you want to do. If you need to read entire file as single 1D numpy array, then you can do it directly (see numpy.fromfile). And if you want to read rows (there are no implicit rows in binary file...) as separate numpy arrays, then perhaps using generator expression that reads one "row" and yields appropriate numpy array would be better way (you could add caching on top of that generator expression). |