0

In Python 2, the following will happily load the first two bytes from a binary file:

with open(file_name) as f:
    b = f.read(2)

However, in Python 3, the same might result in e.g.:

UnicodeDecodeError: 'utf-8' codec can't decode byte 2: invalid start byte

Which brings me to the question: how to read N raw bytes from a file in Python 3 without specifying an encoding?

1 Answer 1

4

Specify binary mode:

with open(file_name, 'rb') as f:

You should do that in Python 2, too, unless you want bugs like CRLFs becoming LFs in your binary file.

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

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.