读取二进制文件的前10个字节(后续操作)-
infile = open('infile.jpg', 'rb')
outfile = open('outfile.jpg', 'wb')
x = infile.read(10)
for i in x:
print(i, end=', ')
print(x)
outfile.write(bytes(x, "UTF-8"))
第一个打印语句显示 -
255, 216, 255, 224, 0, 16, 74, 70, 73, 70,
第二个print语句输出的是 -
b'\xff\xd8\xff\xe0\x00\x10JFIF'
将x中的值转换为十六进制。
outfile.write(bytes(x, "UTF-8"))
返回值 -
TypeError: encoding or errors without a string argument
那么x必须不是普通的字符串,而是一个字节字符串,但仍然是可迭代的吗?
如果我想将x的内容原封不动地写入outfile.jpg,则可以执行以下操作 -
outfile.write(x)
现在我尝试对每个 x[i] 进行某些操作(如下所示,是简单的乘积1),将值赋给 y 并将 y 写入 outfile.jpg,使其与 infile.jpg 相同。因此,我尝试 -
infile = open('infile.jpg', 'rb')
outfile = open('outfile.jpg', 'wb')
x = infile.read(10)
yi = len(x)
y = [0 for i in range(yi)]
j = 0
for i in x:
y [j] = i*1
j += 1
for i in x:
print(i, end=', ')
print(x)
for i in y:
print(i, end=', ')
print(y)
print(repr(x))
print(repr(y))
outfile.write(y)
第一个打印语句(通过x进行迭代)输出 -
255, 216, 255, 224, 0, 16, 74, 70, 73, 70,
第二个打印语句输出的是 -
b'\xff\xd8\xff\xe0\x00\x10JFIF'
第三个打印语句(遍历y)输出结果为:
255, 216, 255, 224, 0, 16, 74, 70, 73, 70,
print语句的作用是 -
[255, 216, 255, 224, 0, 16, 74, 70, 73, 70]
最后,按照Tim的建议,打印repr(x)和repr(y)分别得到以下结果 -
b'\xff\xd8\xff\xe0\x00\x10JFIF'
[255, 216, 255, 224, 0, 16, 74, 70, 73, 70]
文件写入语句出现错误 -
TypeError: 'list' does not support the buffer interface
我需要的是y与x具有相同的类型,使得outfile.write(x) = outfile.write(y)
我凝视着Python的眼睛,但仍然看不到它的灵魂。
outfile.write(bytes(s, "UTF-8"))
。 - Hunter McMillen