Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the size of a TemporaryFile in python? [duplicate]

Tags:

python

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?

like image 340
Dr.Knowitall Avatar asked Apr 20 '18 05:04

Dr.Knowitall


2 Answers

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

like image 166
fasta Avatar answered Nov 06 '22 13:11

fasta


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
like image 22
avigil Avatar answered Nov 06 '22 14:11

avigil