0

I read data from a file as binary data like

with open(filename, "rb") as filein:
    content = filein.read()
print(type(content[0]))

and I expected the data type of the data read to be byte, but I get int.

How to read data from a file as type byte (i.e. the python structure where I put a "b" in from of i like

mybyte = b"bytes"

so I can "add" them to other byte strings?

What I actually want to do is essentially this:

# Read the complete(!) content of the file
with open(filename, "rb") as filein:
    content = filein.read()

# Create new content, where I manipulate some single bytes
# For simplicity this is not shown here
new_content = b""
for byte in content:
    # some manipulating of single bytes, omitted for simplicity
    new_content += byte

# Write the modified content again to a new file
# In this very example, it should replicate the exact same file
with open(filename + "-changed", "wb") as fileout:
    fileout.write(new_content)

But here I get an error

 Traceback (most recent call last):
  File "break_software.py", line 29, in <module>
    new_content += byte
TypeError: can't concat int to bytes
Alex
  • 41,580
  • 88
  • 260
  • 469

1 Answers1

0

This is how bytes works in python, consider that

mybyte = b"bytes"
print(mybyte[0])  # 98
print(type(mybyte[0]))  # <class 'int'>
Daweo
  • 31,313
  • 3
  • 12
  • 25