You must make sure that everything file1.txt creates file1.txt the file descriptor.
The file record is buffered, and if you do not close the file, the buffer will not be cleared. Missing data at the end of the file is still in this buffer.
It is advisable that the file be closed using the file object as the context manager:
with open('file1.txt', 'w') as openfile:
source share