Python读取和写入二进制文件

bre*_*ett 5 binary file python-3.x

以下是我的问题

读取二进制文件的前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"))
Run Code Online (Sandbox Code Playgroud)

第一份印刷声明给出了 -

255, 216, 255, 224, 0, 16, 74, 70, 73, 70, 
Run Code Online (Sandbox Code Playgroud)

第二份印刷声明给出 -

b'\xff\xd8\xff\xe0\x00\x10JFIF'
Run Code Online (Sandbox Code Playgroud)

x中值的十六进制解释.

outfile.write(bytes(x, "UTF-8"))
Run Code Online (Sandbox Code Playgroud)

回报 -

TypeError: encoding or errors without a string argument
Run Code Online (Sandbox Code Playgroud)

那么x必须不是普通字符串,而是字节字符串,它仍然是可迭代的?

如果我想将x的内容写入outfile.jpg,那么我就去 -

outfile.write(x)
Run Code Online (Sandbox Code Playgroud)

现在我尝试取每个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)
Run Code Online (Sandbox Code Playgroud)

第一个打印语句(迭代x)给出 -

255, 216, 255, 224, 0, 16, 74, 70, 73, 70,
Run Code Online (Sandbox Code Playgroud)

第二份印刷声明给出 -

b'\xff\xd8\xff\xe0\x00\x10JFIF'
Run Code Online (Sandbox Code Playgroud)

第三个印刷语句(迭代y)给出 -

255, 216, 255, 224, 0, 16, 74, 70, 73, 70,
Run Code Online (Sandbox Code Playgroud)

印刷声明给出 -

[255, 216, 255, 224, 0, 16, 74, 70, 73, 70]
Run Code Online (Sandbox Code Playgroud)

最后,正如Tim所建议的那样,打印repr(x)和repr(y)分别给出了 -

b'\xff\xd8\xff\xe0\x00\x10JFIF'
[255, 216, 255, 224, 0, 16, 74, 70, 73, 70]
Run Code Online (Sandbox Code Playgroud)

并且文件写入语句给出了错误 -

TypeError: 'list' does not support the buffer interface
Run Code Online (Sandbox Code Playgroud)

我需要的是y与x的类型相同,以便outfile.write(x)= outfile.write(y)

我盯着Python的眼睛,但我仍然没有看到它的灵魂.

Tim*_*ers 3

它们根本不一样——它们只是在应用到它们之后显示相同(这是隐式的)。打印它们,您就会看到差异。例子:str()print()repr()

>>> x = b'ab'
>>> y = "b'ab'"
>>> print(x)
b'ab'
>>> print(y) # displays identically
b'ab'
>>> print(repr(x)) # but x is really a 2-byte bytes object
b'ab'
>>> print(repr(y)) # and y is really a 5-character string
"b'ab'"
Run Code Online (Sandbox Code Playgroud)

混合字符串和字节对象没有意义(好吧,在没有显式编码的情况下没有意义 - 但你并没有尝试在这里编码/解码任何内容,对吧?)。如果您正在使用二进制文件,那么您根本不应该使用字符串 - 您应该使用bytesorbytearray对象。

所以问题并不在于你的写作方式:在此之前逻辑从根本上是混乱的。

猜不到你想要什么。请编辑问题以显示您要完成的任务的完整、可执行示例。为此,我们不需要 JPG 文件 - 组成一些简短的任意二进制数据。喜欢:

dummy_jpg = b'\x01\x02\xff'
Run Code Online (Sandbox Code Playgroud)