我在Python中完全是新手,我有以下问题。
从我在文档中看到的声明
字节数组
不允许我分配不在0到255范围内的值。
事实上这样做:
data = bytearray(1000)
for i in range(len(data)):
data[i] = 10 - i
for b in data:
print(hex(b))
我得到以下例外情况:
Traceback (most recent call last):
File "main.py", line 4, in <module>
data[i] = 10 - i
ValueError: byte must be in range(0, 256)
所以第一个问题:这到底是什么意思?这意味着我可以声明一个最多包含256字节的字节数组?还是我遗漏了什么?如果这个推理是正确的:在我必须读取包含256字节以上的二进制文件的情况下,我如何处理这种情况?
此外,在另一个示例中,我发现此代码段用于将数据从源二进制文件复制到目标二进制文件:
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()
如您所见,它正在声明一个包含255个以上元素的bytearray:
buffer = bytearray(65536)
我想我错过了什么。它到底是如何工作的?