Reputation: 5
First time python app, so of course it's not been easy ;) In plain English this is what I'm trying to do:
read a binary file in, if any bytes are 0x00 change them to 0xFF, otherwise add 0x01 to each byte and write to a new file.
So there it is..my hope is something like
./convert.py file1.bin file2.bin
Here's what I have so far:
#!/usr/bin/env python3
import sys
with open(sys.argv[1], "rb") as f:
byte = f.read(1)
while byte:
# Do stuff with byte.
if byte = b'\x00'
byte = b'\xFF'
else
byte = byte + b'\x01'
byte = f.read(1)
but that's all I have so far...clearly this is very broken. I figured this would be a good learning opportunity...thanks for any assistance you might be able to give.
Upvotes: 0
Views: 849
Reputation: 1046
First, you have a bug in the if byte = b'\x00'
line, you meant ==
. This is one of the most dangerous bugs in software development and that's why python doesn't allow assignment inside a condition.
Second, better check for the length of byte because python reads bytes from file as a list of bytes
. So, in the end of the file you will get an empty list of bytes
.
Now for the code:
#!/usr/bin/env python3
import sys
with open(sys.argv[1], "rb") as fin, open(sys.argv[2], "wb") as fout:
byte = fin.read(1)
while len(byte):
# Do stuff with byte.
if byte == b'\x00'
byte = b'\xFF'
else
byte = bytes((ord(byte) - 1,))
fout.write(byte)
byte = fin.read(1)
Upvotes: 1