6.6.3 假脱机文件
如果临时文件中包含的数据相对较少,则使用SpooledTemporaryFile可能更高效,因为它使用一个io.BytesIO或io.StringIO缓冲区在内存中保存内容,直到数据达到一个阈值大小。当数据量超过这个阈值时,数据将“滚动”并写入磁盘,然后用常规的TemporaryFile()替换这个缓冲区。
import tempfile
with tempfile.SpooledTemporaryFile(max_size=100,mode='w+t',
encoding='utf-8') as temp:
print('temp:{!r}'.format(temp))
for i in range(3):
temp.write('This line is repeated over and over.\n')
print(temp._rolled,temp._file)
这个例子使用SpooledTemporaryFile的私有属性来确定何时滚动到磁盘。除非要调整缓冲区大,否则很少需要检查这个状态。
运行结果:
要显示地将缓冲区写至磁盘,可以调用rollover()或fileno()方法。
import tempfile
with tempfile.SpooledTemporaryFile(max_size=1000,mode='w+t',
encoding='utf-8') as temp:
print('temp:{!r}'.format(temp))
for i in range(3):
temp.write('This line is repeated over and over.\n')
print(temp._rolled,temp._file)
print('rolling over')
temp.rollover()
print(temp._rolled,temp._file)
在这个例子中,由于缓冲区非常大,远远大于实际的数据量,所以除非调用rollover(),否则不会在磁盘上创建任何文件。
运行结果: