将文件粘贴到python中的新文件中
问题描述:
有没有办法打开/创建filehandle = open("example.bin", "wb")
并使用现有文件扩展此文件?将文件粘贴到python中的新文件中
我想 有点像.extend
从功能列表,像这样:
filehandle = open("example.bin", "wb")
filehande.extend(existing_file.bin)
我知道我可以读取现有的文件和写一个变量/列表和“粘贴”,它在新的文件,但即时通讯好奇,如果有这样的一个更容易的选择...
答
with open('original', 'a') as out_file, open('other', 'r') as ins_file:
out_file.write(ins_file.read())
这将在other
内容附加到original
。如果您正在处理二进制数据,则可以将每个模式更改为ab
和rb
。
如果文件内容很大,你也可以do it in chunks。
答
您不能合并文件对象。可以使每个文件的列表和扩展他们
files_combined = list(open("example.bin", "wb")) + list(open("file_2"))
将返回一个列表的所有在file_2
附加file_1
线,但在一个新的列表。然后,您可以将其保存到新文件,或覆盖其中一个文件。
文件句柄只是一个文件对象,而不是一个列表 – Harsha
我知道,如果你两次阅读我的问题,我问了一个类似的方法。 – Nico
'cat file1 file2> file3'在终端上运行它。 –