9

Currently when I write to a temporary:

import tempfile
a = tempfile.TemporaryFile()

a.write(...)

# The only way I know to get the size
a.seek(0)
len(a.read())

Is there a better way?

Dr.Knowitall
  • 9,340
  • 22
  • 79
  • 125
  • 7
    Not a duplicate, the other question asks about a regular file not temporary file which has no path. – Dr.Knowitall Apr 20 '18 at 17:38
  • the already-answered stackoverflow thread does not have any solution related to temporary files (especially `SpooledTemporaryFile`), this post should be reopened – Han Jul 17 '21 at 16:32

2 Answers2

16
import tempfile
a = tempfile.TemporaryFile()
a.write('abcd')
a.tell()
# 4

a.tell() gives you the current position in the file. If you are only appending this will be accurate. If you are jumping around the file with seek, then seek to the end of the file first with: a.seek(0, 2) the second parameter "whence"=2 means the position is relative to the end of the file. https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

fasta
  • 321
  • 1
  • 5
11

You can use os.stat assuming the file has either been closed or all pending writes have been flushed

os.stat(a.name).st_size
avigil
  • 2,131
  • 10
  • 17