Manipulating binary data in Python

前端 未结 7 1333
旧时难觅i
旧时难觅i 2021-02-07 07:16

I am opening up a binary file like so:

file = open(\"test/test.x\", \'rb\')

and reading in lines to a list. Each line looks a little like:

7条回答
  •  梦谈多话
    2021-02-07 07:25

    Are you using read() or readline()? You should be using read(n) to read n bytes; readline() will read until it hits a newline, which the binary file might not have.

    In either case, though, you are returned a string of bytes, which may be printable or non-printable characters, and is probably not very useful.

    What you want is ord(), which converts a one-byte string into the corresponding integer value. read() from the file one byte at a time and call ord() on the result, or iterate through the entire string.

提交回复
热议问题