pythonpython-3.xpython-bytearray

How exactly works the use of bytearray in Python?


I am absolutly new in Python and I have the following question.

From what I read on the documentation declaring a byte array I am not allowed to assign a value that doesn't come from the range 0 to 255.

Infact doing something like this:

data = bytearray(1000)

for i in range(len(data)):
    data[i] = 10 - i

for b in data:
    print(hex(b))

I am obtaining the following exception:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    data[i] = 10 - i
ValueError: byte must be in range(0, 256)

So first question: what exactly does it mean? It means that I can declare an array of bytes containing at most 256 bytes? Or am I missing something? If this reasoning is correct: in the case that I have to read a binary file containing more than 256 bytes how can I handle this situation?

Furthermore in another example I found this code snippet used to copy data from a source binary file to a destination one:

from os import strerror

srcname = input("Source file name?: ")
try:
    src = open(srcname, 'rb')
except IOError as e:
    print("Cannot open source file: ", strerror(e.errno))
    exit(e.errno)   
dstname = input("Destination file name?: ")
try:
    dst = open(dstname, 'wb')
except Exception as e:
    print("Cannot create destination file: ", strerr(e.errno))
    src.close()
    exit(e.errno)   

buffer = bytearray(65536)
total  = 0
try:
    readin = src.readinto(buffer)
    while readin > 0:
        written = dst.write(buffer[:readin])
        total += written
        readin = src.readinto(buffer)
except IOError as e:
    print("Cannot create destination file: ", strerr(e.errno))
    exit(e.errno)   

print(total,'byte(s) succesfully written')
src.close()
dst.close()

As you can see it is declaring a bytearray containing more than 255 element:

buffer = bytearray(65536)

I think that I am missing something. How exactly does it work?


Solution

  • The message is pretty clear: each value in the array must be a byte, and a "byte must be in range(0, 256)". It says nothing about how many elements can be in the array.