0

I have a binary file called "input.bin". I am practicing how to work with such files (read them, change the content and write into a new binary file). the contents of input file:

03 fa 55 12 20 66 67 50 e8 ab

which is in hexadecimal notation.

I want to make a output file which is simply the input file with the value of each byte incremented by one.

here is the expected output:

04 fb 56 13 21 67 68 51 e9 ac

which also will be in hexadecimal notation. I am trying to do that in python3 using the following command:

with open("input.bin", "rb") as binary_file:
    data = binary_file.read()
    for item in data:
        item2 = item+1
    with open("output.bin", "wb") as binary_file2:
        binary_file2.write(item2)

but it does not return what I want. do you know how to fix it?

4
  • What is it returning? Commented May 2, 2019 at 20:51
  • With current indentations you execute write only once - after for loop - so it can write only one value. Open both files in one with at start, and put write inside for loop. Commented May 2, 2019 at 20:54
  • Also, you're using item-1 when your explanation and expected output both suggest you mean item+1 Commented May 2, 2019 at 20:56
  • Please do not deface the original post because it makes the existing comments and answer/s non-understandable. You can instead put your explanation as a comment or as an answer. Commented May 3, 2019 at 9:39

1 Answer 1

5

You want to open the output file before the loop, and call write in the loop.

with open("input.bin", "rb") as binary_file:
    data = binary_file.read()

with open("output.bin", "wb") as binary_file2:
    binary_file2.write(bytes(item - 1 for item in data))
Sign up to request clarification or add additional context in comments.

2 Comments

bytes is, I think, a little asymmetrical; it's easy to get an int from a bytes, but less easy to turn a single int back into a bytes object.
The update shows a relatively efficient way to process multiple bytes; the struct module is another option.

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.