以下是我的问题重新措辞Python的读取和写入到二进制文件
读前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"))
第一个print语句让 -
255, 216, 255, 224, 0, 16, 74, 70, 73, 70,
第二打印语句使 -
b'\xff\xd8\xff\xe0\x00\x10JFIF'
x的值的十六进制解释。
outfile.write(bytes(x, "UTF-8"))
回报 -
那么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)
第一个print语句(通过X迭代)让 -
255, 216, 255, 224, 0, 16, 74, 70, 73, 70,
第二打印语句使 -
b'\xff\xd8\xff\xe0\x00\x10JFIF'
第三个print语句(至Y迭代)给出 -
255, 216, 255, 224, 0, 16, 74, 70, 73, 70,
print语句给人 -
[255, 216, 255, 224, 0, 16, 74, 70, 73, 70]
最后,印刷再版(x)和再版(Y),由Tim的建议,给了分别 -
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的眼睛,但我仍然没有看到它的灵魂。
看看这篇文章:http://stackoverflow.com/questions/5471158/typeerror-str-does-not-support-the-buffer-interface似乎是在Python 2和Python 3之间改变了String类。 –
Hunter - 我用outfile.write(s.encode('UTF-8')替换了outfile.write(s)并且没有收到任何错误!但是使用infile.read()导致outfile.jpg的大小是infile的两倍。 jpg和破坏我想要完成的是读取二进制文件,执行操作,反转该操作并将输出写入单独的文件以使它们完全相同 – brett
在后面的答案中,我链接了使用的'outfile.write (bytes(s,“UTF-8”));' –