将文件粘贴到 python 中的新文件中

Paste file in new file in python

有没有办法 open/create filehandle = open( "example.bin", "wb") 并使用现有文件扩展此文件?

我想像 .extend from function for lists 像这样:

filehandle = open( "example.bin", "wb")
filehande.extend(existing_file.bin)

我知道我可以读取现有文件并将其写入新文件中的 variable/list 和 "paste" 但我很好奇是否有像这样更简单的选项...

with open('original', 'a') as out_file, open('other', 'r') as ins_file:
    out_file.write(ins_file.read())

这会将 other 的内容附加到 original 上。如果您正在处理二进制数据,您可以将每个模式更改为 abrb.

如果文件内容很大,您也可以do it in chunks

您不能合并文件对象。您可以列出每个文件并扩展它们

files_combined = list(open("example.bin", "wb")) + list(open("file_2"))

将 return 一个列表,其中 file_2 中的所有行附加到 file_1,但在一个新列表中。然后您可以将其保存到新文件,或覆盖其中一个文件。