1

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.

2
  • 1
    Have you tried b_f=open("image.bin", "rb").read()? Commented Nov 5, 2015 at 15:01
  • Not yet, I will try thanks a lot, but how can I specify there that it should be read as raw string? Commented Nov 5, 2015 at 15:10

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for your answer!
1

If you wish to read the entire file into memory, simply calling the file's read() method (with no arguments) will do.

Eg:

s = open("image.bin", "rb").read()

If you only wish to read up to a specific number of bytes (as in @Eric Dill's example), that can be passed as a parameter to the read method:

s = open("image.bin", "rb").read(SOME_NUMBER_OF_BYTES)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.