Python 将两个二进制文件合并为第三个二进制文件

Python 将两个二进制文件合并为第三个二进制文件,python,file,batch-file,binary,copy,Python,File,Batch File,Binary,Copy,我试图在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) 这段代码没有给我任何错误,但它没有生成预期的输出 例如,如果我编写了批处理命令来合并文

我试图在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)
i、 e.使用二进制模式写入,但这给了我以下错误:

TypeError:需要类似字节的对象,而不是“str” 正确的流程是什么

有关早期错误,请参阅以下内容:

这个解决方案不起作用


使用Python 3.7,我认为应该打开两个输入文件,分块读取它们,然后写入一个输出文件:

from shutil import copyfileobj
from io import DEFAULT_BUFFER_SIZE

with open('input1.bin', 'rb') as input1, open('input2.bin', 'rb') as input2, open('output.bin', 'wb') as output:
    copyfileobj(input1, output, DEFAULT_BUFFER_SIZE)
    copyfileobj(input2, output, DEFAULT_BUFFER_SIZE)


出现此错误的原因是TypeError:在Python3中写入文件时需要类似字节的对象,而不是“str”,原因是: 您以文本模式(默认模式)读取文件,因此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)

读取二进制文件时,应以“b”二进制模式打开它们。i、 打开'input1.bin','rb'。读取这将为您提供字节对象而不是字符串。读取文本格式的文件是导致主要错误的原因。谢谢你指出这一点。