Why am I missing last 16 bytes with serial communication?

You call f.write with 1023, instead of with len, so its going to miss every 1024'th character and write lots of
junk bytes at the end of the file.

The last 16 bytes thing is probably at the other end of the serial connection where something is reseting
without waiting for the serial buffer to drain.