如何在python中获取TemporaryFile的大小?

时间:2018-04-20 05:28:55

标签: python

目前我写一个临时的:

import tempfile
a = tempfile.TemporaryFile()

a.write(...)

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

有更好的方法吗?

2 个答案:

答案 0 :(得分:2)

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

a.tell()为您提供文件中的当前位置。如果你只是附加这将是准确的。如果您使用seek跳转文件,请首先使用以下命令查找文件的末尾: a.seek(0, 2)第二个参数“whence”= 2表示该位置相对于文件末尾。 https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

答案 1 :(得分:0)

假设文件已关闭或所有待处理的写入已被刷新,您可以使用os.stat

os.stat(a.name).st_size