【发布时间】:2014-01-07 05:49:59
【问题描述】:
以下是我的问题重新措辞
读取二进制文件的前 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,
第二个打印语句给出-
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] 并对每个 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,
打印语句给出-
[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)
我凝视着蟒蛇的眼睛,但还是看不到它的灵魂。
【问题讨论】:
-
看看这篇文章:stackoverflow.com/questions/5471158/… 似乎 String 类在 Python 2 和 Python 3 之间发生了变化。
-
Hunter - 我用 outfile.write(s.encode('UTF-8') 替换了 outfile.write(s) 并且没有收到错误!但是使用 infile.read() 导致 outfile.jpg大小是 infile.jpg 的两倍并且损坏。我要完成的是读取二进制文件,执行操作,反转该操作并将输出写入单独的文件,以使它们相同。
-
我链接的帖子中的答案使用了
outfile.write(bytes(s, "UTF-8"));
标签: file python-3.x binary