我有一个测试设置方法,我创建了一个tempfile.NamedTemporaryFile。我想要测试的代码需要读取该文件的内容。当它这样做时,看起来文件是空的。
import tempfile
fp1 = tempfile.NamedTemporaryFile()
fp1.write('foo')
fp2 = open(fp1.name)
print fp2.read() # I expect "foo" here
答案 0 :(得分:1)
发生这种情况的原因是写入方法是“缓冲”的 换句话说,并非所有对文件系统的write()调用都会立即产生 在磁盘上的变化。有很多方法可以解决这个问题:
写入()后flush()
import tempfile
fp1 = tempfile.NamedTemporaryFile()
fp1.write('foo')
fp2 = open(fp1.name)
# Because of buffering we've not yet written to the file.
assert fp2.read() == ''
fp1.flush()
# We've now explicitly written to the file.
assert fp2.read() == 'foo'
fp1.close()
fp2.close()
或者你可以将缓冲设置为0,这是一种丑陋的说法“不要 缓冲但立即写入磁盘“。
# Let's do it again, but now use buffering.
fp1 = tempfile.NamedTemporaryFile(bufsize=0)
fp1.write('foo')
fp2 = open(fp1.name)
# Because we've set buffering to 0 (so no buffering) we've written to the
# file.
assert fp2.read() == 'foo'
fp1.close()
fp2.close()