The problem is here
while os.stat(filename).st_size < size:
Both input and output are buffered on computers. First create a list of what you want to write and check the size each time. Then use .join() to write the file. Writing each number to the file is inefficient and slower anyway, so keep the data in memory where you have more control.
Also, Python has universal newline support so you can just use "\n".