【发布时间】:2020-09-14 22:07:03
【问题描述】:
我正在尝试将两个二进制文件合并到 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
此命令生成大小为 150KB 的 Output.bin,而早期的 python 命令将输出文件大小为 151KB。
我也试过了:
with open('Output.bin', 'wb') as fp:
fp.write(input1)
即使用二进制模式编写,但这给了我错误:
TypeError: a bytes-like object is required, not 'str'
什么是正确的过程?
参考这个早期的错误:TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3
此解决方案不起作用。
使用 Python 3.7
【问题讨论】:
-
读取二进制文件时,应以
'b'二进制模式打开。即open('input1.bin', 'rb').read()这将为您提供字节对象而不是字符串。
标签: python file batch-file binary copy