Search code examples
pythonbinaryfilesrawstring

How to open a binary file as raw string in python?


I have a macro written in imageJ script. I need to rewrite this macro to python3.4. I have opened a binary file in reading mode:

b_f = open("image.bin", "rb")
OverScan = 0
sizeY = 480
reg = OverScan + 10

Then I came into problems when trying to find a way how to open b_f as a raw string. In imageJ script it looks like that: s=File.openAsRawString(b_f,2*192*(1+sizeY)*reg); File.openAsRawString(path, count) - Opens a file and returns up to the first count bytes as a string.

Is there some easy way in python how to open a binary file as raw string? I am totally new to python. Thanks for your help in advance.


Solution

  • After you have opened a file, that file reference has a read() method on it which takes the number of bytes that you want to read in.

    with open("image.bin", "rb") as b_f:
        OverScan = 0
        sizeY = 480
        reg = OverScan + 10
        binary_data = b_f.read(2*192*(1+sizeY)*reg)
    

    binary_data will now be of type bytes and hold the number of bytes that you have asked for