Differences between write and tempfile.write

Please explain the following:

def feed(data):
  import os
  print "DATA LEN: %s" % len(data)
  f = open("copy", "w")
  f.write(data)
  f.close()
  print "FILE LEN: %s" % os.stat("copy").st_size
  t = tempfile.NamedTemporaryFile()
  t.write(data)
  print "TEMP LEN: %s" % os.stat(t.name).st_size
  t.close()

feed(x)
DATA LEN: 11004
FILE LEN: 11004
TEMP LEN: 8192

Why is there a difference, and can I fix the pace? The end seems to be chopping.

Tested on 2.6, 2.7

+4
source share
1 answer

I think you are working with the internal size of a write buffer. In the first case, you are a .close()file before the call os.stat, which effectively clears the internal buffer. In the second case (c tempfile), you still open the file when you call os.stat. Since the file is still open, some of them may be buffered in memory until you are flushexplicitly or closed.

+4
source

Source: https://habr.com/ru/post/1528077/


All Articles