简体   繁体   中英

read and write binary files in python

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?

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM