目前,当我写入一个临时文件时:
import tempfile
a = tempfile.TemporaryFile()
a.write(...)
# The only way I know to get the size
a.seek(0)
len(a.read())
有更好的方法吗?
目前,当我写入一个临时文件时:
import tempfile
a = tempfile.TemporaryFile()
a.write(...)
# The only way I know to get the size
a.seek(0)
len(a.read())
有更好的方法吗?
import tempfile
f = tempfile.TemporaryFile()
f.write('abcd')
f.tell()
# 4
f.tell()
返回一个整数,表示文件对象在二进制模式下从文件开头算起的字节数,而在文本模式下则返回一个不透明的数字,表示当前位置。
如果您正在使用 seek 跳转文件,请先使用以下代码将其定位到文件末尾:a.seek(0, 2)
第二个参数 "whence"=2 表示相对于文件末尾的位置。
https://docs.python.org/3.11/tutorial/inputoutput.html#methods-of-file-objects
a.write('abcd')
? - mkamioner假设文件已经关闭或所有挂起的写操作都已刷新,您可以使用os.stat
。
os.stat(a.name).st_size
SpooledTemporaryFile
)相关的解决方案,因此应该重新打开此帖子。 - Ham