0

I am new to binary files and trying to figure out how to read and manipulate them. I have the following code:

bfile = open('square.bmp', 'wb')

b = bytearray(bfile.read(bn))

while len(b) > 0:
    b = bytearray(bfile.read(bn))
    print(b)

bfile.close()

However, running this code is throwing errors and I do not know what I can replace the "bn" with or declare it as to run read the entire file.

4
  • Check this other question, it may be useful: stackoverflow.com/questions/1035340/… Commented Nov 28, 2013 at 20:23
  • bn is an undefined variable. Typically, read() takes a size as a parameter, so you might want to start there. Commented Nov 28, 2013 at 20:24
  • by the way, open(..., 'wb') recreates file, so you'll rean nothing Commented Nov 28, 2013 at 20:26
  • More fundamentally ;-), you opened the file for writing (w), not for reading. Change the open mode to 'rb'. Commented Nov 28, 2013 at 20:26

1 Answer 1

0
with open("square.bmp", "rb") as f:
   b = f.read(1)
   while b != b"":
      b = f.read(1)
Sign up to request clarification or add additional context in comments.

4 Comments

Are you checking for EOF or empty string?
@Keikoku read returns '' on eof.
In binary mode, it returns b''
@Keikoku I guess you meand for py3, I'm not used to it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.