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

Dr.*_*all 6 python

目前,当我写一个临时:

import tempfile
a = tempfile.TemporaryFile()

a.write(...)

# The only way I know to get the size
a.seek(0)
len(a.read())
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

fas*_*sta 13

import tempfile
a = tempfile.TemporaryFile()
a.write('abcd')
a.tell()
# 4
Run Code Online (Sandbox Code Playgroud)

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


avi*_*gil 8

您可以os.stat假设文件已关闭或所有挂起的写入已刷新

os.stat(a.name).st_size
Run Code Online (Sandbox Code Playgroud)