6

我想复制一个文件,然后开始编写新文件:

shutil.copyfile("largefile","newlargefile")
nwLrgFile=open("newlargefile",'a')
nwLrgFile.write("hello\n")

但是,当我执行上述操作时,hello会在文件末尾之前写入。确保完成复制文件的正确方法是什么?

我查看了 SO 和其他地方,但我看到的所有答案都说 shutil.copyfile 阻塞或锁定,这应该不是问题。然而,确实如此。请帮忙!

4

1 回答 1

3

尝试copyfileobj直接使用:

with open('largefile', 'r') as f1, open('newlargefile', 'w') as f2:
    shutil.copyfileobj(f1, f2)
    f2.write('hello')
于 2013-02-07T00:55:39.577 回答