我正在尝试将两个二进制文件合并到Python 中的第三个二进制文件。我的代码:
input1 = input2 = ""
input1 = open('input1.bin').read()
input2 = open('input2.bin').read()
input1 += input2
with open('Output.bin', 'w') as fp:
fp.write(input1)
这段代码没有给我任何错误,但这没有生成预期的输出。
就像,如果我编写批处理命令来合并文件:
copy /b input1.bin+input2.bin Output.bin
该命令正在生成Output.bin
大小为 150KB,而之前的 python 命令给出的输出文件大小为 151KB。
我也尝试过这个:
with open('Output.bin', 'wb') as fp:
fp.write(input1)
即使用二进制模式编写,但这给了我错误:
TypeError: a bytes-like object is required, not 'str'
正确的过程是什么?
针对之前的错误引用了此:类型错误:在 Python3 中写入文件时需要类似字节的对象,而不是“str”
该解决方案不起作用.
使用Python 3.7
出现此错误的原因( TypeError: a bytes-like object is required, not 'str' when write to a file in Python3)是因为:
您以文本模式(这是默认模式)读取文件,因此 input1 和 input2 变成字符串,并且您尝试以二进制模式将它们写回(您需要 input1 成为类似字节的对象)。一种方法是以二进制模式读取文件本身,如下所示。
# Try reading the file in binary mode and writing it back in binary
# mode. By default it reads files in text mode
input1 = open('input1.bin', 'rb').read()
input2 = open('input2.bin', 'rb').read()
input1 += input2
with open('Output.bin', 'wb') as fp:
fp.write(input1)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)