将二进制文件附加到另一个二进制fi

2024-04-25 05:29:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想附加一个以前写的二进制文件和一个最近创建的二进制文件。 基本上是合并它们。这是我正在使用的示例代码:

with open("binary_file_1", "ab") as myfile:
    myfile.write("binary_file_2")

除了我得到的错误是"TypeError: must be string or buffer, not file"

但这正是我想要做的!在先前创建的二进制文件的末尾添加一个二进制文件。

我确实试着把"wb"添加到"myfile.write("binary_file_2", "wb")中,但它不喜欢这样。


Tags: 文件代码示例abas错误with二进制
3条回答

您需要实际打开第二个文件并读取其内容:

with open("binary_file_1", "ab") as myfile, open("binary_file_2", "rb") as file2:
    myfile.write(file2.read())
for file in files:
    async with aiofiles.open(file, mode='rb') as f:
        contents = await f.read()
    if file == files[0]:
        write_mode = 'wb'  # overwrite file
    else:
        write_mode = 'ab'  # append to end of file

    async with aiofiles.open(output_file), write_mode) as f:
        await f.write(contents)

从python模块shutil

import os
import shutil

WDIR=os.getcwd()
fext=open("outputFile.bin","wb")
for f in lstFiles:
    fo=open(os.path.join(WDIR,f),"rb")
    shutil.copyfileobj(fo, fext)
    fo.close()
fext.close()

首先打开outputFile.bin二进制文件进行写入,然后使用shuil.copyfileobj(src,dest)循环lstFiles中的文件列表,其中src和dest是文件对象。要获取文件对象,只需使用正确的模式“rb”read binary对文件名调用open来打开文件。对于打开的每个文件对象,我们必须将其关闭。连接的文件也必须关闭。 我希望能帮上忙

相关问题 更多 >