Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wait for shutil.copyfile to finish

I want to copy a file then start writing the new file:

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

However, when I do the above hello will be written before the end of the file. What is the right way to make sure copyfile is done?

I looked on SO and other places but all the answers I saw said that shutil.copyfile blocks or locks and that it shouldn't be a problem. And yet, it is. Please help!

like image 484
a113nw Avatar asked Feb 07 '13 00:02

a113nw


1 Answers

Try using copyfileobj directly instead:

with open('largefile', 'r') as f1, open('newlargefile', 'w') as f2:
    shutil.copyfileobj(f1, f2)
    f2.write('hello')
like image 185
nneonneo Avatar answered Sep 22 '22 06:09

nneonneo