11

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
  • 10,080
  • 23
  • 82
  • 133
  • 10
    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 – Ham Jul 17 '21 at 16:32

2 Answers2

20
import tempfile
f = tempfile.TemporaryFile()
f.write('abcd')
f.tell()
# 4

f.tell() returns an integer giving the file object’s current position in the file represented as number of bytes from the beginning of the file when in binary mode and an opaque number when in text mode.

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/3.11/tutorial/inputoutput.html#methods-of-file-objects

UselesssCat
  • 2,248
  • 4
  • 20
  • 35
fasta
  • 361
  • 1
  • 5
12

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,218
  • 11
  • 18